Short answer: Your computation is numerically unsound.
Long answer:
The termination condition looks funny indeed. From a pure mathematical standpoint x1/x0
is equal to x/n
, so the condition actually means x/n > e
, and one would expect the loop to run until n = x/e
, in your case to 5000000
. However, the unfriendly nature of floating point strikes again, and the loop breaks much earlier, at n = 539
. Upon loop termination the debugger shows that x1
is literally 0
. For the record, x0
at this point is 4.94E-324
, and on the next iteration double
ran out of mantissa bits.
It may look inconceivable that numbers as small as 4.94E-324
may significantly affect the result. In fact your problems start much earlier than that.
Look how terms of the sequence behave: they grow while n
is less then x
, and start decreasing after that. The maximum is obviously achieved at \$n \approx x\$, and is equal to \$\frac{x^x}{x!} \approx \frac{x^x}{\sqrt{2\pi x}}\$ (by Stirling approximation). That is, for \$x = 50\$ the 50'th term is just 1/17'th of the result, and the accumulated sum is already in order of E21
of magnitude. The terms meanwhile start to decrease, and you find yourself in a very unfortunate situation:
you add small values to large ones.
To add two floating point values, the summator must align them to the same exponent. This means that the smaller value inevitably loses some bits of mantissa. There goes precision, and what's even worse, the whole mantissa may disappear: that is from the certain n
terms stop to contribute whatsoever. For x = 50
underflow happen at n = 119
, and the first completely lost term is about 269909
. Considering further lost terms, that it is quite in line with the 9437184
error you've got.
Solution:
The huge intermediate result defeats small terms one by one. Together they can defend. Start from the small numbers (that is large n
) and work your way down to n = 0
. The Horner schema was specifically designed to deal with issues you are facing.