Skip to content

Instantly share code, notes, and snippets.

@seanbreckenridge
Created February 9, 2023 07:14
Show Gist options
  • Save seanbreckenridge/2d550a52dac052b0f3cfac038a2a6afc to your computer and use it in GitHub Desktop.
Save seanbreckenridge/2d550a52dac052b0f3cfac038a2a6afc to your computer and use it in GitHub Desktop.
from typing import Iterator, TypeVar
from decimal import Decimal
it = int(input("Enter number of iterations: "))
def calculate_pi(till: int, factory: TypeVar) -> Iterator[int]:
approx = factory(0)
denom = factory(1)
for i in range(till):
if i % 2 == 0:
approx += factory(1) / denom
else:
approx -= factory(1) / denom
denom += 2
yield approx * 4
int_pi = calculate_pi(it, int)
dec_pi = calculate_pi(it, Decimal)
for i, (int_res, dec_res) in enumerate(zip(int_pi, dec_pi)):
print(f"int: {int_res} | dec: {dec_res} | diff: {abs(dec_res - Decimal(int_res))}")
if i >= it:
break
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment