Python PI precision function
xxxxxxxxxx
from decimal import Decimal, getcontext
from typing import Iterator
class PiCalculator:
def __init__(self, digits: int):
self.digits = digits
getcontext().prec = digits + 1
def bbp_term(self, k: int) -> Decimal:
"""
Calculate the k-th term of the Bailey-Borwein-Plouffe (BBP) formula.
Args:
k (int): The index of the term.
Returns:
Decimal: The k-th term of the BBP formula.
"""
term = Decimal(1) / (16 ** k)
a = Decimal(4) / (8 * k + 1)
b = Decimal(2) / (8 * k + 4)
c = Decimal(1) / (8 * k + 5)
d = Decimal(1) / (8 * k + 6)
return term * (a - b - c - d)
def pi_digits(self) -> Decimal:
"""
Calculate Pi to the specified number of digits using the Bailey-Borwein-Plouffe (BBP) formula.
Returns:
Decimal: The value of Pi to the specified number of digits.
"""
pi = Decimal(0)
for k in range(self.digits):
pi += self.bbp_term(k)
return pi
def display(self):
pi_value = self.pi_digits()
print(f"Pi to {self.digits} digits: {pi_value:.{self.digits}f}")
if __name__ == "__main__":
calculator = PiCalculator(50)
calculator.display()