Python的圆周率计算? [英] Python pi calculation?

查看:766
本文介绍了Python的圆周率计算?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一个Python的初学者,我想计算圆周率。我试着用楚德诺夫斯基算法,因为我听说它比其他算法快。

I am a python beginner and I want to calculate pi. I tried using the Chudnovsky algorithm because I heard that it is faster than other algorithms.

这是我的code:

from math import factorial
from decimal import Decimal, getcontext

getcontext().prec=100

def calc(n):
    t= Decimal(0)
    pi = Decimal(0)
    deno= Decimal(0)
    k = 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**(1.5))
    pi = 1/pi
    return pi

print calc(25)

由于某种原因,与可接受的值相比,这个code PI产生向上的vakue只有15小数。我试图通过增加precision值来解决这一点;这增加的位数,但只有前15仍然准确。我试图改变它计算算法的方式,并没有擦出火花。所以我的问题是,是有什么可以做这个code,使之更准确或我将不得不使用另一种算法?的我想AP preciate帮助,这因为我不知道怎么有这么多的蟒蛇位操作。我想是能够控制的确定,并通过该程序显示(正确)的位数 - 无论10,100,1000,等

For some reason this code yields the vakue of pi up to only 15 decimals as compared with the acceptable value. I tried to solve this by increasing the precision value; this increases the number of digits, but only the first 15 are still accurate. I tried changing the way it calculates the algorithm and it didn't work either. So my question is, is there something that can be done to this code to make it much more accurate or would I have to use another algorithm? I would appreciate help with this because I don't know how to operate with so many digits in python. I would like to be able to control the number of (correct) digits determined and displayed by the program -- whether 10, 100, 1000, etc.

推荐答案

看来你失去precision在这一行:

It seems you are losing precision in this line:

pi = pi * Decimal(12)/Decimal(640320**(1.5))

请尝试使用:

Try using:

pi = pi * Decimal(12)/Decimal(640320**Decimal(1.5))

这是因为,即使Python可以处理任意规模的整数,它不与花车做的这么好。

This happens because even though Python can handle arbitrary scale integers, it doesn't do so well with floats.

奖金

用另一种算法单行实现( BBP公式):

A single line implementation using another algorithm (the BBP formula):

from decimal import Decimal, getcontext
getcontext().prec=100
print sum(1/Decimal(16)**k * 
          (Decimal(4)/(8*k+1) - 
           Decimal(2)/(8*k+4) - 
           Decimal(1)/(8*k+5) -
           Decimal(1)/(8*k+6)) for k in range(100))

这篇关于Python的圆周率计算?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆