#Estimating pi based on Ramanujan's formula and Chudnovsky algorithm
import math

def estimate_pi(iterations):
    # Initialize the sum
    sum_term = 0.0

    # Perform the summation
    for k in range(iterations):
        term1 = math.factorial(4 * k) * (1103 + 26390 * k)
        term2 = (math.factorial(k) ** 4) * (396 ** (4 * k))
        sum_term += term1 / term2

    # Calculate the reciprocal of the sum
    reciprocal_sum = 2 * math.sqrt(2) / 9801 * sum_term

    # Estimate pi
    pi_estimate = 1 / reciprocal_sum

    return pi_estimate

def estimate_pi_chudnovsky(iterations):
    sum_term = 0
    for k in range(iterations):
        numerator = ((-1) ** k) * math.factorial(6 * k) * (13591409+545140134*k)
        denominator = math.factorial(3 * k) * (math.factorial(k) ** 3) * (640320 ** (3 * k))
        sum_term += numerator / denominator
        total_sum=math.sqrt(10005)/4270934400 * sum_term
    return 1/total_sum

# Number of iterations for the approximation
iterations = 10

# Calculate the estimated value of pi
estimated_pi = estimate_pi(iterations)
estimatedc_pi = estimate_pi_chudnovsky(iterations)

# Compare with the actual value of pi
actual_pi = math.pi
#actual_pi=3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679

print(f"Estimated pi (Ramanujan):", "%.20f" % estimated_pi)
print(f"Estimated pi (Chudnovsky algorithm):", "%.20f" % estimatedc_pi)
print(f"Actual pi (approx.): ", "%.20f" % actual_pi)

Embed on website

To embed this project on your website, copy the following code and paste it into your website's HTML: