我正在尝试使用Python和此Wikipedia页面来教自己Chudnovsky的算法:
,我专注于“高性能迭代实现,[]可以简化为:
在Wiki上 “ rel =“ nofollow noreferrer”>
我试图在远面的方程式上进行编码正确的是使用Sigma符号。我对Python很熟悉,但在数学方面并不那么出色。我为自己设定的目标是看看我是否可以准确打印出至少100位PI数字。
公式中有5组括号,因此我尝试对5个不同组件中的每个组件进行编码。我还写了一个可以执行阶乘的函数,因为阶乘在5个组件/括号中的3个中使用。
这是我的23行工作代码,有人可以帮助我理解为什么它不能准确地使用100位数字吗?它准确地转到第28位:3.1415926535897932384626433832。然后,对于第29位,它说8,但应该是7 ...
import math
from decimal import *
def factorial(n):
if n == 0:
return 1
memory = n
for i in range(1, n):
memory *= i
return memory
iterations = 500
_sum = 0
#here's the Sigma part
for q in range(0, iterations):
a = factorial(6*q)
b = (545140134*q) + 13591409
c = factorial(3*q)
d = (factorial(q))**3
e = (-262537412640768000)**q
numerator = (a*b)
denominator = (c*d*e)
_sum += Decimal(numerator / denominator)
#ensures that you get 100 digits for pi
getcontext().prec = 100
sq = Decimal(10005).sqrt()
overPI = Decimal(426880 * sq)
pi = (overPI) * (Decimal(1 / _sum))
print("Pi is", pi)
谢谢您提供的任何帮助。
I am trying to teach myself Chudnovsky's algorithm using Python and this wikipedia page:
https://en.wikipedia.org/wiki/Chudnovsky_algorithm
On the wiki, I am focused on the "high performance iterative implementation, [that] can be simplified to":

I tried to code up the equation on the far right that is using the Sigma symbol. I am familiar with Python but am not that great at math. The goal I set for myself is to see if I can accurately print out at least 100 digits of pi.
There are 5 sets of parentheses in the formula so I tried to code up each of the 5 different components. I also wrote a function that does factorials because factorials are used in 3 of the 5 components/parentheses.
Here's my 23 lines of working code, can someone please help me understand why it does not ACCURATELY go to 100 digits? It accurately goes to the 28th digit: 3.1415926535897932384626433832. Then for the 29th digit it says 8 but it should be 7...
import math
from decimal import *
def factorial(n):
if n == 0:
return 1
memory = n
for i in range(1, n):
memory *= i
return memory
iterations = 500
_sum = 0
#here's the Sigma part
for q in range(0, iterations):
a = factorial(6*q)
b = (545140134*q) + 13591409
c = factorial(3*q)
d = (factorial(q))**3
e = (-262537412640768000)**q
numerator = (a*b)
denominator = (c*d*e)
_sum += Decimal(numerator / denominator)
#ensures that you get 100 digits for pi
getcontext().prec = 100
sq = Decimal(10005).sqrt()
overPI = Decimal(426880 * sq)
pi = (overPI) * (Decimal(1 / _sum))
print("Pi is", pi)
Thank you for any assistance that you're able to provide.
发布评论
评论(1)
在文件的 start 上设置小数精度,以便将其应用于所有后续操作:
在除分配或乘法之前,将操作数转换为
DECIMAL
:< /p>结果 - 精确到98 dp(100 sf减去舍入错误):
Set the decimal precision at the start of the file so that it is applied to all subsequent operations:
Convert either or both operands to
Decimal
before dividing or multiplying:Result - accurate to 98 d.p. (100 s.f. minus rounding error):