Page 1 sur 1

calcul de py en python

Posté : mar. sept. 17, 2024 11:48 pm
par phpbb

Code : Tout sélectionner

import decimal

def pi_bbp(digits):
    decimal.getcontext().prec = digits + 2
    pi = decimal.Decimal(0)
    for k in range(digits):
        pi += (decimal.Decimal(1) / 16**k) * (
            decimal.Decimal(4) / (8*k + 1) -
            decimal.Decimal(2) / (8*k + 4) -
            decimal.Decimal(1) / (8*k + 5) -
            decimal.Decimal(1) / (8*k + 6)
        )
    return pi

if __name__ == "__main__":
    while True:
        try:
            digits = int(input("Enter the number of digits to calculate for pi: "))
            if digits <= 0:
                raise ValueError("Number of digits must be positive.")
            break
        except ValueError as e:
            print(e)

    calculated_pi = pi_bbp(digits)
    print(f"Pi with {digits} digits is approximately: {calculated_pi:.{digits}f}")