Pi is calculating wrong

Advertisements

So ive been more into pi and formulas and all that. I thought pi was cool, so I looked up how to calculate it in Python. I used multiple formulas, but it took forever. Then I stumbled upon the Chudnovsky formula. I looked it up, and pasted the whole formula into Pycharm. It didn’t work it printed 163096908.00. What? Not even close! I looked on Wikipedia and they had a Python script! copied it and, it did work but it printed in and array. Please help! I Can’t figure it out and AI keeps telling me the same thing! Here’s the code:

import math
import time
def chudnovsky(n):
    k = 0
    pi_sum = 0
    while k < n:
        pi_sum += (-1) ** k * math.factorial(6 * k) * (545140134 * k + 13591409) /    (math.factorial(3 * k) * (math.factorial(k)) ** 3 * 640320 ** (3 * k))
        k += 1
    return 12 * pi_sum

start_time = time.time()
n = int(input("10 ** >"))
digits = 10 ** n
calculated_pi = chudnovsky(digits)
end_time = time.time()
final_time = start_time - end_time
print(f"Pi to decimal places: {calculated_pi:.{n}f}")
print(f"Calculation time: {final_time}")

I didn’t know what was wrong. There was no errors, just a number that was wrong, and when I wanted over 2 digits then it printed multiple decimals at the end. Hopefully someone can help!

>Solution :

Use Decimal for higher precision and also set higher precision:

import decimal


def chudnovsky(n):
    decimal.getcontext().prec = n + 15
    C = 426880 * decimal.Decimal(10005).sqrt()
    K = decimal.Decimal(13591409)
    M, X = decimal.Decimal(1), decimal.Decimal(1)
    L = decimal.Decimal(545140134)
    S = K

    for i in range(1, n):
        M = (M * (12 * i - 11) * (12 * i - 7) * (12 * i - 5) * (12 * i - 1)) / (i ** 3 * 640320 ** 3)
        K += L
        X *= -262537412640768000
        S += decimal.Decimal(M * K) / X

    pi = C / S
    return pi


n = 5
calculated_pi = chudnovsky(n)
print(f"Pi to {n} decimal places: {str(calculated_pi)[:n + 15]}")

Prints

Pi to 5 decimal places: 3.141592653589734207

Leave a ReplyCancel reply