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.)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…