Question

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 (result >= 1.0E-20 )
{
    power = power * input;
    factorial = factorial * counter;
    result = power / factorial;
    eValue += result;
    counter++;
    iterations++;
}

My problem now is that since factorial is of type long long, I can't really store a number greater than 20! so what happens is that the program outputs funny numbers when it reaches that point ..

The correct solution can have an X value of at most 709 so e^709 should output: 8.21840746155e+307

The program is written in C++.

Was it helpful?

Solution

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

OTHER TIPS

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

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top