Python - 尝试计算 pi 的数字,但无法超过小数点后 48 位数字

问题描述 投票:0回答:2

我正在尝试编写一个程序来使用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)
python decimal precision pi
2个回答
1
投票

您没有使用 Decimal 类来计算 Pi,而是使用 float 类。

getcontext()
影响 Decimal,而不是 float。

如果您想使用 Decimal,请修改代码以在循环之前转换为 Decimal。请注意,据我所知,Pi 的值在 Python 中不能以十进制形式提供,因此您需要从其他地方获取该值(http://www.geom.uiuc.edu/~huberty/math5337/groupe/digits)。 html)。


0
投票
这里可以了,但是我对超过30位的数字没有耐心。 200 需要很长很长的时间。

# 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
    
© www.soinside.com 2019 - 2024. All rights reserved.