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)
一個簡單的解決方法是計算下一個數字,並將整個數字保存在一個字符串中,然後追加。 –
getcontext()用於小數。 https://docs.python.org/3/library/decimal.html你的計算是使用浮點數 – Mic
請注意,你實際上並沒有在這裏計算pi到50位的精度。您正在計算一個精確到math.pi給出的值的50個十進制數字之內的數字,該數字本身只能精確到浮點數可以保留的有效數字的大約16或17個左右。 – Mic