why is np.exp(x) not equal to np.exp(1)**x

Viewed 234

Why is why is np.exp(x) not equal to np.exp(1)**x?

For example:

np.exp(400)
>>>5.221469689764144e+173

np.exp(1)**400
>>>5.221469689764033e+173

np.exp(400)-np.exp(1)**400
>>>1.1093513018771065e+160
2 Answers

It looks like a rounding issue. In the first case it's internally using a very precise value of e, while in the second you get a less precise value, which when multiplied 400 times the precision issues become more apparent.

The actual result when using the Windows calculator is 5.2214696897641439505887630066496e+173, so you can see your first outcome is fine, while the second is not.

5.2214696897641439505887630066496e+173         // calculator
5.221469689764144e+173                         // exp(400)
5.221469689764033e+173                         // exp(1)**400

Starting from your result, it looks it's using a value with 15 digits of precision.

2.7182818284590452353602874713527         // e
2.7182818284590450909589085441968         // 400th root of the 2nd result

This is optimisation of numpy that raise this diff.

Indeed, you have to understand how is calculated the Euler number in math:

e = (1/n)**n with n == inf.

I think numpy stop at a certain order:

You have in the numpy exp documentation here that is not very clear about how the Euler number is calculated.

Because of this order that is not equal to infinity, you have this small difference in the two calculations.

Indeed the value np.exp(400) is calculated using this: (1 + 400/n)**n

>>> (1 + 400/n)**n                                                                                                      
5.221642085428121e+173                                                                                                  
>>> numpy.exp(400)                                                                                                      
5.221469689764144e+173

Here you have n = 1000000000000 wich is very small and raise this difference at 10e-5.

Indeed there is no exact value of the Euler number. Like Pi, you can only have an approched value.

Related