2017-01-09 222 views
10

我製作了一個Python 3程序來計算學校項目的pi值,但它總是停在小數點後16位。 python中的數字長度是否有限制?如果有,我可以使用的語言會讓我繼續嗎?python有數字限制嗎?

accuracy = int(input("accuracy: ")) 

current = 2 
opperation = "+" 
number = 3 
count = 1 

for i in range (accuracy): 
    if opperation == "-": 
     number = number - (4/(current*(current+1)*(current+2))) 
     opperation = "+" 
    elif opperation == "+": 
     number = number + (4/(current*(current+1)*(current+2))) 
     opperation = "-" 
    current += 2 
    print(str(count).zfill(8)) + ": " + str(number) 
    count += 1 
+2

使用'decimal'模塊可以避免長度限制,對於您的情況重要的是避免浮點不精確。 –

+0

使用給定大小的浮點數可以獲得精度限制。但是Python會讓你顯示更多的數字:'從數學導入pi;打印(格式(pi,'.32f'))'。 – jonrsharpe

+0

如果你想確切知道你係統上的浮點數是多少,'import sys; print(sys.float_info)' –

回答

9

如果使用整數和Python 3.x,沒有限制。然而,你使用浮點數的精度是有限的。正如你所說,一個Python float(如3.14)實際上是一個C double,它有大約16位的精度。

您可以使用decimal模塊以任意精度創建和處理其他浮點數。示例代碼:

# Normal Python floats 
a = 0.000000000000000000001 
b = 1 + 2*a 
print(b) # Prints 1.0 

# Using Decimal 
import decimal 
decimal.getcontext().prec = 100 # Set the precision 
a = decimal.Decimal('0.000000000000000000001') 
b = 1 + 2*a 
print(b) # Prints 1.000000000000000000002 

有關decimal的更多信息請參見the docs

+0

請注意,使用小數將比內置在浮點數字中。 – Richard

+2

@Richard的確。雖然在Python3.3中,'decimal'模塊[加速](https://docs.python.org/3/whatsnew/3.3.html#new-decimal)大約爲100倍!對於較新版本的Python,它應該不會有問題。 –

+0

我認爲值得注意的是,在小數模塊的文檔中,有一個配方來計算pi – Copperfield