2013-03-29 28 views
2

我試圖得到一個長整型Python的math.sqrt損精

from math import sqrt 
print sqrt(410241186411534352) 

<< 640500731.0 

開方值它返回640500731.0,這的確是640500730.999999993 ...精度。如何解決這個問題?

我根據@DSM和@ Rob的回覆解決了這個問題,非常感謝。

from math import sqrt 
from decimal import Decimal 
print Decimal(410241186411534352).sqrt() 
+0

如果你需要一個整數平方根函數,見[這個問題](http://stackoverflow.com/questions/15390807/integer-square-root-in-python)的幾個選項。 – DSM

回答

2
>>> import decimal 
>>> decimal.getcontext().prec = 100 
>>> a=decimal.Decimal(410241186411534352)**decimal.Decimal(.5) 
>>> print a 
640500730.9999999929742468943411712910588335443486974564849183256021518032770726219326459594197730639 
>>> print a*a 
410241186411534352.0000000000000000000000000000000000000000000000000000000000000000000000000000000000 
>>> 
2

Python的數學庫函數是圍繞C數學庫函數薄包裝紙,所以Python是轉換長整型到雙尺寸的浮點數執行計算之前。如果你想在Python中使用真正的多精度算術,你可以試試mpmath

+0

任何更改我可以用純python解決這個問題,沒有其他的包? –

+2

@AaronJiang:你可以使用'decimal'模塊。 – DSM

+0

@DSM,非常感謝,對我來說十進制作品 –