Given a number x. You need to calculate sum of Taylor Series of e^x.
e^x = 1 + x + x^2/2! + x^3/3! + ...
Calculate sum until a general number is lower or equal to 10^(-9).
Down below is my solution but it is wrong for x<0 numbers. Do you have any idea how to fix this to work for negative numbers.
int x,i,n;
long long fact; //fact needs to be double
double sum=0,k=1;
scanf("%d",&x);
i=0; sum=0; k=1;
while (fabs(k)>=1.0E-9) {
fact=1;
for (int j=1;j<=i;++j)
fact*=j;
k=pow(x,i)/fact;
sum+=k;
++i;
}
printf("%lf\n",sum);
fact needs to be double, it can not be long long because of divides.
Your problem is that your factorial computation overflows and becomes garbage. After that your
ith
term doesn't decrease anymore and produce completely wrong results.After 20 iterations a 64 bits number cannot contains the value of
20!
. See: http://www.wolframalpha.com/input/?i=21%21%2F2%5E64If
x^n/n!
is not inferior to your threshold (1e-9
) whenn=20
then your computation ofn!
will overflow even a 64 bits integer. When that happens you will get the value ofn!
modulo2^63
(I simplify because you didn't use an unsigned integer and you will get random negative value instead but the principle remains). These values may be very low instead of being very high. And this will cause yourx^n/n!
to become greater instead of smaller.You should not use the
pow
function for raising a (possibly negative) number to an integer power. Instead use repeated multiplication as you do to compute the factorial.Notice also that you could store the last computed values of $n!$ and $x^k$ to obtain $(n+1)!$ and $x^{k+1}$ with a single multiplication.