Calculating e^x without using any functions

[亡魂溺海] 提交于 2019-11-27 19:32:34

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

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

lakshmanaraj

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.

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!