2017-05-24 54 views
-2

我在Python 3使用特殊功能lambertw(k=-1),我需要用數字用它高於/低於最大/最小浮點數較低(1.7976931348623157e+308) 。使用一個較大的數字比最大浮動的特殊功能lambertw

我該怎麼辦?

另外我嘗試使用「小數」,但它沒有工作,我。即,

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''  
+1

你能做的就是上傳你的它爲什麼沒有WO的解釋試圖沿着什麼樣的第一件事RK;告訴人們這裏*「我試着用」小數「,但它不起作用。」*沒有幫助。 –

+1

我會驚訝,如果'scipy.special.lambertw'工程與'decimal.Decimal' ... –

回答

1

mpmathSymPy包括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 
+0

謝謝!有用。 – iaraya

2

decimal模塊應該能夠解決您的問題。您遇到的問題可能是您未將精度設置爲高於默認值28,as mentioned in the docs。要做到這一點,只需撥打getcontext().prec = 100或您需要的任何精度即可。

例如,使用例如數字,我只是跑這個交互式會話:

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

我的問題是在lambert函數中使用該數字... – iaraya

+0

啊,感謝您編輯的問題,這是起初很模糊。我做了一些研究,看起來你不能; scipy似乎只支持本地數字類型:https://docs.scipy.org/doc/numpy-1.10.1/user/basics.types.html – Personman