对于特殊函数,请使用大于最大浮点值的数字

2024-09-28 05:24:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我在python3中使用特殊函数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''    

Tags: thetoinfromimportlinenotscipy
2条回答

SymPy中的^{}库包含^{}的实现。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

decimal模块应该能够解决您的问题。您遇到的问题可能是没有将精度设置为高于默认值28as mentioned in the docs。要做到这一点,只需调用getcontext().prec = 100或任何您需要的精度。你知道吗

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

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

相关问题 更多 >

    热门问题