计算 Pi 到第 N 位 [英] Calculating Pi to the Nth digit

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

问题描述

我正在尝试输入一个数字并计算该数字输入的 pi.我设法能够计算 Pi,但是无论我输入什么数字,它仍然会生成相同数量的 Pi 数字.

I'm trying to enter in a number and calculate pi to that digit input. I managed to be able to calculate Pi, however no matter what number I type it will still generate the same amount of Pi numbers.

我有点困惑是什么原因导致这样做

I'm a bit confused at what point it's causing to do that

from math import factorial
from decimal import Decimal, getcontext
# Chudnovsky algorithm for figuring out pi
getcontext().prec=100

pi_input = input('How many digits of pi would you like?')
n = int(pi_input)

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

print calc(n)

这是我的输出

How many digits of pi would you like? 5 

3.141592653589793238462643383279502884197169399375105820974944592307816346
94690247717268165239156011

推荐答案

使用 Chudnovsky 算法,计算每次迭代产生大约 14.18 个十进制数字:log10((640320^3)/(24*6*2*6)) ~= 14.18.这可以在 ak/ak-1 的公式中更清楚地看出,如本网页所示:

Using the Chudnovsky algorithm, the calculation produces about 14.18 decimal digits per iteration: log10((640320^3)/(24*6*2*6)) ~= 14.18. This can be more clearly seen in the formula for ak / ak-1 as shown on this web page:

https://www.craig-wood.com/nick/articles/pi-chudnovsky

对于 n = 5,结果的精度约为 70 位.

For n = 5, the result has about 70 digits of precision.

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

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