我正在尝试通过做各种小项目来学习python,在这种情况下,输入一个数字,pi将计算到该数字输入。在谷歌搜索的帮助下,我设法能够计算Pi,但无论我输入的是什么数字,它仍会产生相同数量的Pi数。
我有点困惑,它导致这样做的任何一点,任何提示将非常感谢,提前感谢。这是在python 2.7上
from math import factorial
from decimal import Decimal, getcontext
# Chudnovsky algorithm for figuring out pi
getcontext().prec=100
pi_input = input('How many digits of pi would you like?')
n = int(pi_input)
def calc(n):
t= Decimal(0)
pi = Decimal(0)
deno= Decimal(0)
for k in range(n):
t = ((-1)**k)*(factorial(6*k))*(13591409+545140134*k)
deno = factorial(3*k)*(factorial(k)**3)*(640320**(3*k))
pi += Decimal(t)/Decimal(deno)
pi = pi * Decimal(12) / Decimal(640320 ** Decimal(1.5))
pi = 1/pi
return pi
print calc(n)
这是我的输出
How many digits of pi would you like? 5
3.141592653589793238462643383279502884197169399375105820974944592307816346 94690247717268165239156011
使用Chudnovsky算法,计算每次迭代产生大约14.18个十进制数字:log10((640320 ^ 3)/(24 * 6 * 2 * 6))〜= 14.18。这可以在本网页所示的ak / ak-1公式中更清楚地看到:
https://www.craig-wood.com/nick/articles/pi-chudnovsky
对于n = 5,结果具有大约70位精度。
您可以使用"%.nf"
to格式输出字符串,其中n
是您要输出的位数。例如
import numpy as np
print "%.5f"%(np.pi)
from math import factorial
from decimal import Decimal, getcontext
n = int(input('How many digits of pi would you like?'))
# Chudnovsky algorithm for figuring out pi
getcontext().prec=n+1
def calc(n):
t= Decimal(0)
pi = Decimal(0)
deno= Decimal(0)
k=0
#t = ((-1)**k)*(factorial(6*k))*(13591409+545140134*k)
t=(1)*(factorial(1))*(13591409+545140134*k)
deno = factorial(3*k)*(factorial(k)**3)*(640320**(3*k))
pi += Decimal(t)/Decimal(deno)
pi = pi * Decimal(12) / Decimal(640320 ** Decimal(1.5))
pi = 1/pi
return pi
print (calc(n))
这可能是一个简单的理解代码
from numpy import *
n = int(input('How many digits of pi after decimal would you like to print'))
print(pi)
#print (" value of pi at {:.4f} is" .format(pi))
print('{pi:0.{precision}f}'.format(pi=pi,precision=n))
我就是这样做的:-)
import math
digits = int(input("to how many digits to you want to round PI?"))
def roundpi(n):
return round(pi,n)
roundpi(digits)