Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculating e^x without using any functions

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

like image 995
Charles Khunt Avatar asked May 06 '09 02:05

Charles Khunt


2 Answers

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

like image 89
ShreevatsaR Avatar answered Oct 18 '22 02:10

ShreevatsaR


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

like image 41
Greg Hewgill Avatar answered Oct 18 '22 00:10

Greg Hewgill