taylor series swaping signs problem

hey guys am trying to compute a sinx taylor series but am unable to swap the + - signs in the sequence....my code is only adding...here is the sequence sinx=x-x^3/3!+x^5/5!-x^7/7!...................pls help am stuck.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
  #include <iostream>
#include <cmath>
#include <fstream>
#include <vector>
using namespace std;
void getValuesFromFile(vector<double>&X)
{
    double x=0.0;

    ifstream infile("indata.txt");
    while(infile>>x)
    {
        X.push_back(x);
    }
}
double factorial(unsigned long number)
{
    if(number<=1)
        return 1;
    else
        return number*factorial(number - 1);
}

void calculate(vector<double> X)
{
    double total;
    total=0.0;

    for(int i=1;i<=8;i +=2 )
    {
        total=total+pow(X[0],i)/factorial(i);
    }
    cout<<total<<endl;
}

int main()
{
   vector<double> X;
    getValuesFromFile(X);
    calculate(X); 
    return 0;
}
To alternate from - to + there are several ways the easiest way would be to do something like:

1
2
3
4
5
6
7
8
int sign = 1;
int result = 10;

//add
result += 2 * sign; //add 2

sign *= -1;
result += 2 * sign; //subtract 2 


so you would put that inside your loop

Or you could multiply by pow( -1 , i ); but that may be a bit more expensive.
thanx I got it to work:).....cud u also help me make it work without using the power function but loops
1
2
3
4
5
6
int sign = -1;
for(int i=1;i<=8;i +=2 )
{
    sign *= -1;
    total += pow(X[0],i)/factorial(i) *sign;
}


Topic archived. No new replies allowed.