如何使用scipy和非常大的数字

时间:2018-01-20 21:09:09

标签: python scipy scientific-computing

我想使用scipy的特殊功能来处理非常大的数字

alpha = 9999
def y(t):
    return 1 / (special.lambertw(alpha * math.exp(alpha-t)) + 1)

math.exp抛出溢出错误,这并不奇怪。所以我尝试使用十进制模块

alpha = 9999
def y(t):
    exp = decimal.Decimal(math.exp(1))
    exp = exp ** alpha
    exp = exp * decimal.Decimal(math.exp(-t))
    return 1 / (special.lambertw(alpha * math.exp(alpha-t)) + 1)

但是得到以下错误:

TypeError: ufunc '_lambertw' not supported for the input types, and the 
inputs could not be safely coerced to any supported types according to 
the casting rule ''safe''

special.lambertw来自scipy

处理此问题的正确方法是什么?

1 个答案:

答案 0 :(得分:3)

一种选择是使用mpmath。它包括lambertw的实现。

例如,

In [20]: import mpmath

In [21]: mpmath.mp.dps = 30

In [22]: alpha = 9999

In [23]: def y(t):
    ...:     return 1 / (mpmath.lambertw(alpha * mpmath.exp(alpha-t)) + 1)
    ...: 

In [24]: y(1.5)
Out[24]: mpf('0.000100015000749774938119797735952206')

一般情况下,您无法使用具有极大值的scipy特殊功能。大多数scipy代码都是用C,C ++或Fortran实现的,并且仅限于64位浮点值,最大值约为1.8e308:

In [11]: np.finfo(np.float64).max
Out[11]: 1.7976931348623157e+308
相关问题