使用大于特殊函数 lambertw 的最大浮点数的数字



我在Python 3中使用特殊函数lambertw(k=-1(,我需要将其与高于/小于最大/最小浮点数(1.7976931348623157e+308(的数字一起使用。

我能做什么?

我也尝试使用"十进制",但它不起作用,即

from decimal import Decimal
from scipy.special import lambertw
lambertw(Decimal('3.1E+600'))

得到这个,

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/share/apps/sistema/Python-3.5.1/lib/python3.5/site-packages/scipy/special/lambertw.py", line 107, in lambertw
return _lambertw(z, k, tol)
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''    

decimal模块应该能够解决您的问题。您遇到的问题可能是您没有将精度设置为高于默认值 28,如文档中所述。为此,只需调用getcontext().prec = 100或您需要的任何精度。

例如,使用您的示例编号,我刚刚运行了此交互式会话:

>>> decimal.getcontext().prec = 1000
>>> d = decimal.Decimal(1.7976931348623157e+308)
>>> d
Decimal('179769313486231570814527423731704356798070567525844996598917476803157260780028538760589558632766878171540458953514382464234321326889464182768467546703537516986049910576551282076245490090389328944075868508455133942304583236903222948165808559332123348274797826204144723168738177180919299881250404026184124858368')

SymPy 中的mpmath库包含 lambertw 的实现。 mpmath实现任意精度浮点运算。

下面是一个示例。 首先,从sympy导入mpmath,并将精度的数字设置为 100(任意选择 - 更改以满足您的需求(:

In [96]: from sympy import mpmath
In [97]: mpmath.mp.dps = 100

验证 mpmath 函数是否给出与 scipy.special.lambertw 相同的结果:

In [98]: from scipy.special import lambertw
In [99]: lambertw(123.45)
Out[99]: (3.5491328966138256+0j)
In [100]: mpmath.lambertw(123.45)
Out[100]: mpf('3.549132896613825444243187580460572741065183903716765715536934583554830913412258511917029758623080475405')

计算lambertw(3.1e600) . 参数作为字符串输入,因为我们不能将 3.1e600 表示为常规浮点值。 mpmath将使用我们之前设置的精度将字符串转换为高精度浮点值。

In [101]: mpmath.lambertw('3.1e600')
Out[101]: mpf('1375.455917376503282959382815269413629072666427317318260231463057587794635136887591876065911283365916388')

我们还可以创建一个变量x来保存输入值,然后调用mpmath.lambertw(x)

In [102]: x = mpmath.mpf('3.1e600')
In [103]: x
Out[103]: mpf('3.099999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999e+600')
In [104]: mpmath.lambertw(x)
Out[104]: mpf('1375.455917376503282959382815269413629072666427317318260231463057587794635136887591876065911283365916388')

结果可以表示为常规浮点值,因此我们将其传递给内置函数float()进行转换:

In [105]: float(mpmath.lambertw(x))
Out[105]: 1375.455917376503

相关内容

最新更新