The Chudnovsky Formula in Python

谁说我不能喝 提交于 2021-01-24 09:30:42

问题


I'm trying to implement the Chudnovsky algorithm for calculating pi. I am using formulas from this description https://www.craig-wood.com/nick/articles/pi-chudnovsky/

Now it's working, but maximum number of digits it can show is 3.141592653589793238462643385 - only 27 digits.

Why does Python limits the number of digits in this script? May be i am using Decimal in wrong way?

Here is my code (updated):

from decimal import Decimal, getcontext
from math import factorial
import sys

def calculate_pi(max_K, number_of_digits):
    getcontext.prec = number_of_digits+2
    a_k, b_k, C, a_sum, b_sum  =  1, 0, 640320, 1, 0
    for k in range(1,max_K):
        a_k *= -(Decimal(24)/Decimal(C**3))*Decimal((6*k-5)*(2*k-1)*(6*k-1))/Decimal(k**3)
        a_sum += a_k
        b_sum += a_k*k


    pi = 426880*Decimal(10005).sqrt()/Decimal(13591409*a_sum + 545140134*b_sum)
    print str(pi)[:number_of_digits+2]

def main(number_of_digits):
    pi = calculate_pi(10000, number_of_digits)


if __name__ == "__main__":
    number_of_digits = int(sys.argv[1])
    main(number_of_digits)

回答1:


First of, this site is not a bug-searching site. However I was interested in the problem, and checked out the site you mentioned.

If you look at the definition of a, then you see that the first summand is 1, and not -6*5*4/640320^3. Also since you start your loop at k = 1, you additionally need to assign the variables a_sum and b_sum with the first summands a_0 = 1 and b_0 = 0.




回答2:


Use getcontext().prec = ... instead of getcontext.prec = ...



来源:https://stackoverflow.com/questions/50906200/the-chudnovsky-formula-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!