2017-07-03 109 views
0

我正在嘗試編寫一個程序來使用python中的Nilakantha系列來計算pi的數字。每次運行它都不會給我超過50個小數。仍然學習python,所以任何幫助表示讚賞。Python - 試圖計算pi的數字,並且在十進制後無法獲得48位數字

# Program using Nilakantha Series to crunch digits of pi 
from math import * 
from decimal import * 

getcontext().prec = 200 # this is not doing anything 

# epsilon is how accurate I want to be to pi 
EPSILON = 0.000000000000000000000000000000000000000000000000000001 

sum = float(3) 
step = 0 

i = 2 

while abs(pi - sum) >= EPSILON: 
    step += 1 
    print (step) 
    if step % 2 == 1: 
     sum += 4.0/(i * (i + 1) * (i + 2)) 
     i += 2 
    else: 
     sum -= 4.0/(i * (i + 1) * (i + 2)) 
     i += 2 

print (Decimal(sum)) 
print (Decimal(pi)) 
print ("Total itterations: ", step) 
print ("Accurate to: ", EPSILON) 
+0

一個簡單的解決方法是計算下一個數字,並將整個數字保存在一個字符串中,然後追加。 –

+0

getcontext()用於小數。 https://docs.python.org/3/library/decimal.html你的計算是使用浮點數 – Mic

+1

請注意,你實際上並沒有在這裏計算pi到50位的精度。您正在計算一個精確到math.pi給出的值的50個十進制數字之內的數字,該數字本身只能精確到浮點數可以保留的有效數字的大約16或17個左右。 – Mic

回答

1

您沒有使用Decimal類來計算Pi,而是使用float類。 getcontext()影響十進制,而不是浮動。

如果要使用十進制,請在循環之前修改您的代碼以轉換爲十進制。請注意,AFAIK,Pi的值在Python中不能用作十進制,因此您需要從其他位置獲取值(http://www.geom.uiuc.edu/~huberty/math5337/groupe/digits.html)。

相關問題