Chudnovsky 算法 returns 负数和不正确的数字 - Python

Chudnovsky algorithm returns a negative and incorrect digits - Python

我正在尝试在 Python 中制作 Chudnovsky 算法:

我只是在使用它的第二部分和第三部分(唯一必要的部分)。这是我的代码:

import decimal
# sets number of digits
decimal.getcontext().prec = 100

def factorial(n):
    fact = decimal.Decimal('1')

    for i in range(1, n + 1):
        fact = fact * i
    return fact

def findPi(numOfDigits):
    k = 0
    result = decimal.Decimal('0')
    next = decimal.Decimal('426880') * decimal.Decimal('10005').sqrt()
    while True:
        a = factorial(6 * k)
        b = 545140134 * k + 13591409
        # top of the chudnovsky algorithm
        top = decimal.Decimal(str(a * b))
        c = factorial(3 * k)
        d = factorial(k) ** 3
        e = -262537412640768000 ** k
        # bottom of the chudnovsky algorithm
        bottom = decimal.Decimal(str(c * d * e))
        result += top / bottom
        print(next / result)
        k += 1
findPi(50)

每当我运行它时,它就是这样returns: -3.141592653589675176874263801479785514507867103418138605371738276354365851084005009510847111434082626

只有第十二位正确,其余不正确(也是负数)

更改此行

e = -262537412640768000 ** k

为了修复负面问题

e = (-262537412640768000) ** k

关于准确率,你应该先计算总和,然后再做你的next/result计算。您正在计算总和的每一步。另外,您的 while 循环需要一个 break 语句,您似乎没有使用 numOfDigits 参数。