Python 中的楚德诺夫斯基公式 [英] The Chudnovsky Formula in Python

查看:22
本文介绍了Python 中的楚德诺夫斯基公式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试实现用于计算 pi 的 Chudnovsky 算法.我正在使用此描述中的公式 https://www.craig-wood.com/nick/articles/pi-chudnovsky/

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/

现在它可以工作了,但它可以显示的最大位数是3.141592653589793238462643385 - 只有 27 位数字.

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

为什么 Python 会限制这个脚本中的位数?可能是我以错误的方式使用了十进制?

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)

推荐答案

首先,这个站点不是一个错误搜索站点.但是我对这个问题很感兴趣,并查看了您提到的网站.

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

如果你看一下a的定义,你会发现第一个被加数是1,而不是-6*5*4/640320^3.此外,由于您在 k = 1 处开始循环,因此您还需要为变量 a_sumb_sum 分配第一个被加数 a_0= 1b_0 = 0.

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.

这篇关于Python 中的楚德诺夫斯基公式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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