Created
February 9, 2023 07:14
-
-
Save purarue/2d550a52dac052b0f3cfac038a2a6afc to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
https://stackoverflow.com/questions/75395204/why-is-this-giving-me-a-bad-estimation-of-pi-leibniz-formula#75395338