Calculating e^x without using any functions

前端 未结 4 2076
执笔经年
执笔经年 2020-12-05 05:47

We are supposed to calculate e^x using this kind of formula:

e^x = 1 + (x ^ 1 / 1!) + (x ^ 2 / 2!) ......

I have this code so far:

while (res         


        
4条回答
  •  一个人的身影
    2020-12-05 06:25

    Both x^n and n! quickly grow large with n (exponentially and superexponentially respectively) and will soon overflow any data type you use. On the other hand, x^n/n! goes down (eventually) and you can stop when it's small. That is, use the fact that x^(n+1)/(n+1)! = (x^n/n!) * (x/(n+1)). Like this, say:

    term = 1.0;
    for(n=1; term >= 1.0E-10; n++)
    {
        eValue += term;
        term = term * x / n;
    }
    

    (Code typed directly into this box, but I expect it should work.)

    Edit: Note that the term x^n/n! is, for large x, increasing for a while and then decreasing. For x=709, it goes up to ~1e+306 before decreasing to 0, which is just at the limits of what double can handle (double's range is ~1e308 and term*x pushes it over), but long double works fine. Of course, your final result ex is larger than any of the terms, so assuming you're using a data type big enough to accommodate the result, you'll be fine.

    (For x=709, you can get away with using just double if you use term = term / n * x, but it doesn't work for 710.)

提交回复
热议问题