Exponential of large negative numbers

2019-09-14 21:08发布

问题:

How does one compute a number such as np.exp(-28000) on Python? The answer is around 5E-12161. I've been told that due to the double-precision floating point format, I would only be able to calculate a number > 1e-2048

回答1:

Try the decimal module.

Decimal(math.exp(1))**-28000


回答2:

Try mpmath for floating-point arithmetic with arbitrary precision

Edit 1:

>>> import mpmath as mp 
>>> import numpy as np
>>> a = np.matrix((0,0)) 
>>> print(a)
[0.0 0.0]
>>> b = mp.matrix(a.tolist())
>>> c = b.apply(mp.exp)
>>> print(c)
[1.0]
[1.0]   


回答3:

You could define a function to calculate the "bigexponent" and apply it to the array (along an axis). But, note that the input array has to be of type int.

# solution courtesy: http://stackoverflow.com/a/43084475/2956066
In [97]: def bigexp(x):
    ...:     return Decimal(math.exp(1))**x


In [98]: np.apply_along_axis(bigexp, 1, arr)    

Efficiency (in descending order)

# twice faster than applying along axis 0
In [115]: %timeit np.apply_along_axis(bigexp, 1, a)
1000 loops, best of 3: 272 µs per loop

In [116]: %timeit np.apply_along_axis(bigexp, 0, a)
1000 loops, best of 3: 465 µs per loop