0

Hi,

I'm new to C++, I'm trying to write a program to compute the sine series for taylor expansion. I've written two codes, but both do not work after a certain point.

(The sine series is: sin x = x - (x^3/3!) + (x^5/5)...etc.)

With the code below, when x=1.5, n=3, I do not get the expected value of .9375, instead I get .375. I think the problem is in the if/else statement.

```
double sineSeries(double x, int n){
double xPower = 0.0;
double factorial = 1.0;
double sineComputed = 0.0;
bool sign = true;
for (int i=1; i<=n; i+=2){
xPower = pow(x,i);
factorial *= i;
if (sign) {
sineComputed += xPower/factorial;
}
else {
sineComputed -= xPower/factorial;
}
sign = !sign;
}
return sineComputed;
}
```

I also tried starting with i=3. Here, I have a problem when x=1.5, n=5; I get 1.25391 instead of 1.00078. Again, I think the problem is in the if/else statement, but I'm not sure where.

```
double sineSeries(double x, int n){
double xPower = 0.0;
double factorial = 3.0;
double sineComputed = x;
bool sign = true;
for (int i=3; i<=n; i+=2){
xPower = pow(x,i);
factorial *= (i-1);
if (sign) {
sineComputed -= xPower/factorial;
}
else {
sineComputed += xPower/factorial;
}
sign = !sign;
}
return sineComputed;
}
```

I prefer the first version of the code actually, so I'd like more advice on how to fix that one up. I could probably fix the second one by myself. =)

Thanks in advance.