# Thread: (Term0 + Term1 - Term2 + Term3) How can I do the alternating plus minus?

1. ## (Term0 + Term1 - Term2 + Term3) How can I do the alternating plus minus?

I am working on a problem involving Taylor's Series of cosine x and sine x. (cosx = 1 - (x^2/2!) + (x^4/4!) - ...)
My only problem is how I can do the alternating plus minus on each term. This is the code I currently have in which I can't still figure out if it is right or wrong.

double cosine(double x)
{
int n, ctr;
double cos;

cos = 0;
n = 2*NUMBER_OF_TERMS;
ctr = NUMBER_OF_TERMS;
while(ctr > 0)
{
ctr--;
cos = cos + (RaiseTo(x, n)/factorial(n));
cos *= -1;
n -= 2;
}
return cos;
}

*Note: We were only allowed to use stdio.h as the header file.

2. Code:
```if (term % 2 == 0) {
x *= -1;
}```
or, if you want to avoid a branch
Code:
```double sign = 1;
while (...) {
x *= sign;
sign *= -1;
}```
Not sure which one would be faster.

3. x *= -1 is also the same as x = -x. The latter would probably be faster in terms of instructions, but a good compiler will probably optimize it.