我正在尝试编写一个程序来使用Python中的Nilakantha系列来计算pi的数字。每次运行它都不会给我超过 50 位小数。仍在学习 python,因此我们将不胜感激。
# 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)
您没有使用 Decimal 类来计算 Pi,而是使用 float 类。
getcontext()
影响 Decimal,而不是 float。
如果您想使用 Decimal,请修改代码以在循环之前转换为 Decimal。请注意,据我所知,Pi 的值在 Python 中不能以十进制形式提供,因此您需要从其他地方获取该值(http://www.geom.uiuc.edu/~huberty/math5337/groupe/digits)。 html)。
# Program using Nilakantha Series to crunch digits of pi
from math import *
from decimal import *
pr = 24
getcontext().prec = pr+2 # set pi's prec
# epsilon is how accurate I want to be to pi
EPSILON = Decimal(1/10**(pr+1))
from mpmath import mp
def a(n):
mp.dps=n+1
return(Decimal(str(mp.pi)))
four = Decimal(4.0)
two = Decimal(2.0)
x = Decimal(3)
step = 0
p = a(pr)
print(f"{p}")
i = two
while abs(p - x) >= EPSILON:
step += 1
if step%10**6 == 0:
w = f"{abs(p-x):.{pr}f}"
val = next((index for index,value in enumerate(w[2:]) if value != '0'), None)
acc = " " * (val+4) + "^" # Accuracy tick mark
print (f"Iteration {step:,}\npi={p}\nmy={x}\n{acc}")
if step%2:
x += four / (i * (i + 1) * (i + 2))
i += two
else:
x -= four / (i * (i + 1) * (i + 2))
i += two
print (f"Calulated={x:.{pr}f}")
print (f"Constant ={p:.{pr}f}")
print (f"Total itterations: {step:,}")
print ("Accurate to: ", EPSILON)
输出为23位:
$ python pi_calc.py
3.1415926535897932384626
Iteration 1,000,000
pi=3.1415926535897932384626
my=3.14159265358979323871117
^
Iteration 2,000,000
pi=3.1415926535897932384626
my=3.14159265358979323849364
^
Iteration 3,000,000
pi=3.1415926535897932384626
my=3.14159265358979323847099
^
Iteration 4,000,000
pi=3.1415926535897932384626
my=3.14159265358979323846537
^
Iteration 5,000,000
pi=3.1415926535897932384626
my=3.14159265358979323846353
^
Iteration 6,000,000
pi=3.1415926535897932384626
my=3.14159265358979323846267
^
Calulated=3.1415926535897932384626
Constant =3.1415926535897932384626
Total itterations: 6,163,925
Accurate to: 9.999999999999999604346980148993092553230786866765862587503680141039208439934782290947623550891876220703125E-24