python如何计算π

python如何计算π,第1张

#coding=utf-8

'''

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):

    if len(argv) !=2:

 告腔    乎友笑   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


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/yw/12485690.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-25
下一篇 2023-05-25

发表评论

登录后才能评论

评论列表(0条)

保存