问题
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);
回答1:
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.
回答2:
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%5E64
If x^n/n!
is not inferior to your threshold (1e-9
) when n=20
then your computation of n!
will overflow even a 64 bits integer. When that happens you will get the value of n!
modulo 2^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 your x^n/n!
to become greater instead of smaller.
回答3:
fact needs to be double, it can not be long long because of divides.
来源:https://stackoverflow.com/questions/33333791/taylor-series-of-function-ex