F.M
F.M

Reputation: 1879

Chudnovsky algorithm returns a negative and incorrect digits - Python

I'm trying to make the Chudnovsky algorithm in Python:

I'm just using the second and third parts of it (the only necessary ones). Here's my code:

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)

Whenever I run it, this is what it returns: -3.141592653589675176874263801479785514507867103418138605371738276354365851084005009510847111434082626

It is only correct up to the twelfth digit, and the rest is incorrect (also the negative)

Upvotes: 0

Views: 80

Answers (1)

Gokberk Gul
Gokberk Gul

Reputation: 150

Change this line

e = -262537412640768000 ** k

to this for fixing the negative issue

e = (-262537412640768000) ** k

About the accuracy, you should first compute the sum, then do your next/result computation. You are calculating in every step of the sum. Also, you need a break statement for your while loop, you seem to not use the numOfDigits argument.

Upvotes: 3

Related Questions