Taylor Series Function

So I am working a a project for my intro C++ class, and I am having some trouble with a function for approximating exp(x) using a taylor series. The taylor series approximations for exp(x) is: 1+x+((x^2)/2!)+((x^3)/3!+...., and I am supposed to approximate to "n" number of terms.

Thus far, my function is this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
double fact(int c)
{
int factorial=1;
for ( int i = 1; i <= c; i++ )
{
factorial *=i;
}
return factorial;
}

double taylor(double x, int n)
{
double approx;
double sum;
double value;
for (int i=1; i<=n; i++)
{
int factorial=1;
factorial*=i;
sum=((pow(x,i))/fact(i));
value+=sum;
}
approx = 1+value;
return approx;


Now this does work if I just run it by itself, i.e. just do something like "cout << taylor(x,n)". But whenever I call this function within another function, it does not work! It is kinda hard to explain, but anyone have any ideas?

Thanks
I just noticed a few minor mistakes in my code above, here is an updated version (still doesn't work)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
double fact(int c)
{
   int factorial=1;
   for ( int i = 1; i <= c; i++ )
   {
      factorial *=i;
   }
   return factorial;
}

double taylor(double x, int n)
{
    double approx;
    double sum;
    double value;
    for (int i=1; i<=n; i++)
    {
        sum=((pow(x,i))/fact(i));
        value+=sum;
    }
    approx = 1+value;
    return approx;
}
value is uninitialized in the function taylor(). Set it to zero on line 15.
Thanks a lot!! It works.
Topic archived. No new replies allowed.