Calculating e^x without using any functions

前端 未结 4 2067
执笔经年
执笔经年 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.)

    0 讨论(0)
  • 2020-12-05 06:27

    I can think of another solution. Let pow(e,x) = pow(10, m) * b where b is >=1 and < 10, then

    m = trunc( x * log10(e) )
    

    where in log10(e) is a constant factor.

    and

    b = pow(e,x)/pow(10, m ) = pow(e,x)/pow(e,m/log10(e)) = pow (e,x-m/log10(e))
    

    By this you get:

    z = x-m/log10(e)
    

    which will be in between 0 to 3 and then use b = pow(e,z) as given by SreevartsR.

    and final answer is

    b is base(significant digit) and m is mantissa (order of magnitude).

    this will be faster than SreevartsR approach and you might not need to use high precisions.

    Best of luck.

    This will even work for when x is less than 0 and a bigger negative, in that case z will be in between 0 to -3 and this will be faster than any other approach.

    Since z is -3 to 3, and if you require first 20 significant digits, then pow(e,z) expression can be evaluated upto 37 terms only since 3^37/37! = ~ 3.2e-26.

    0 讨论(0)
  • 2020-12-05 06:27

    What you presented here is an application of Horner scheme to calculate polynomials.

    0 讨论(0)
  • 2020-12-05 06:39

    What happens if you change the type of factorial from long long to double?

    0 讨论(0)
提交回复
热议问题