繁体   English   中英

Chudnovsky 算法返回一个负数和不正确的数字 - 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)

每当我运行它时,它都会返回: -3.141592653589675176874263801479785514507867103418138605371738276354365851084005009510847111434082626

它只正确到第十二位,rest 不正确(也是负数)

更改此行

e = -262537412640768000 ** k

为此解决负面问题

e = (-262537412640768000) ** k

关于准确性,您应该首先计算总和,然后进行下一个/结果计算。 您正在计算总和的每一步。 此外,您的 while 循环需要一个 break 语句,您似乎没有使用 numOfDigits 参数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM