Taylor series of function e^x

2019-06-14 20:20发布

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);

3条回答
Animai°情兽
2楼-- · 2019-06-14 20:48

fact needs to be double, it can not be long long because of divides.

查看更多
【Aperson】
3楼-- · 2019-06-14 20:49

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.

查看更多
4楼-- · 2019-06-14 21:00

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.

查看更多
登录 后发表回答