Skip to content

Instantly share code, notes, and snippets.

@chemacortes
Created July 20, 2022 13:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chemacortes/86bdb3d798235c08a44afa02003c9b80 to your computer and use it in GitHub Desktop.
Save chemacortes/86bdb3d798235c08a44afa02003c9b80 to your computer and use it in GitHub Desktop.
from itertools import count, takewhile
def calc_pi(error: float = 1e-6) -> float:
terms = (1 / (2 * k - 1) for k in count(1))
it = takewhile(lambda x: 2 * x >= error, terms)
ts = list(x - y for x, y in zip(it, it))
pi = 4 * sum(ts)
calc_pi.error = error
calc_pi.numts = 2 * len(ts)
return pi
pi = calc_pi()
print(
f"El valor de pi con un error de {calc_pi.error:f} : {pi} tras {calc_pi.numts} términos"
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment