Skip to content

Instantly share code, notes, and snippets.

@zzzhc
Forked from deeplook/pi_digits.py
Created April 24, 2019 10:56
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 zzzhc/eac3ccc9336ecd1db52dbb83e5049bae to your computer and use it in GitHub Desktop.
Save zzzhc/eac3ccc9336ecd1db52dbb83e5049bae to your computer and use it in GitHub Desktop.
Generate digits of Pi using a spigot algorithm.
"""
Run the algorithm below using CPython, Cython, PyPy and Numba and compare
their performance. (This is implementing a spigot algorithm by A. Sale,
D. Saada, S. Rabinowitz, mentioned on
http://mail.python.org/pipermail/edu-sig/2012-December/010721.html).
"""
def pi_digits(n):
"Generate n digits of Pi."
k, a, b, a1, b1 = 2, 4, 1, 12, 4
while n > 0:
p, q, k = k * k, 2 * k + 1, k + 1
a, b, a1, b1 = a1, b1, p * a + q * a1, p * b + q * b1
d, d1 = a / b, a1 / b1
while d == d1 and n > 0:
yield int(d)
n -= 1
a, a1 = 10 * (a % b), 10 * (a1 % b1)
d, d1 = a / b, a1 / b1
# >>> list(pi_digits(20))
# [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5, 8, 9, 7, 9, 3, 2, 3, 8, 4]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment