'''
Created on 2014-11-04
@author: Neo
'''
import sys
import math
from decimal import *
def bbp(n):
pi=Decimal(0)
k=0
while k < n:
pi+=(Decimal(1)/(16**k))*((Decimal(4)/(8*k+1))-(Decimal(2)/(8*k+4))-(Decimal(1)/(8*k+5))-(Decimal(1)/(8*k+6)))
k+=1
return pi
def main(argv):
告腔 乎友笑 exit('Usage: BaileyBorweinPlouffe.py <prec> <n>')
getcontext().prec=(int(sys.argv[1]))
my_pi=bbp(int(sys.argv[2]))
accuracy=100*(Decimal(math.pi)-my_pi)/my_pi
print "Pi is approximately "+str(my_pi)
print "Accuracy with math.pi: "+str(accuracy)
岁含
if __name__=="__main__":
main(sys.argv[1:])
result:
d:\workspace\PyDemo>python test.py 10 10
Pi is approximately 3.141592653
Accuracy with math.pi: 1.877369797E-8
d:\workspace\PyDemo>python test.py 25 25
Pi is approximately 3.141592653589793238462644
Accuracy with math.pi: -3.898171852150198570978563E-15
d:\workspace\PyDemo>python test.py 40 40
Pi is approximately 3.141592653589793238462643383279502884195
Accuracy with math.pi: -3.898171832519375446564294863483061824361E-15
d:\workspace\PyDemo>
def pisum(n):pi=3
sign=1
for i in range(1,n+1):
pi+=sign*4.0/((i+1)*(i+2)*(i+3))
sign=-sign
return pi
def piprod(n):
start=2**0.5
清梁 pi=1
for i in range(0,n+1):
答困运 for j in range(0,i):
start=(start+2)**0.5
pi*=start
尺缓 pi=2**(n+2)/pi
return pi
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)