Calculating e^x without using any functions

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

提交回复
热议问题