Exponential of large negative numbers

随声附和 提交于 2019-12-12 01:36:43

问题


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


来源:https://stackoverflow.com/questions/43084364/exponential-of-large-negative-numbers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!