blob: 19733cbf01ba3bed30df3e9bffba8a27f9bddb1a [file] [log] [blame]
Guido van Rossumf06ee5f1996-11-27 19:52:01 +00001#! /usr/bin/env python
Guido van Rossumec758ea1991-06-04 20:36:54 +00002
3# Print digits of pi forever.
4#
5# The algorithm, using Python's 'long' integers ("bignums"), works
6# with continued fractions, and was conceived by Lambert Meertens.
7#
8# See also the ABC Programmer's Handbook, by Geurts, Meertens & Pemberton,
9# published by Prentice-Hall (UK) Ltd., 1990.
10
11import sys
12
13def main():
Collin Winter6f2df4d2007-07-17 20:59:35 +000014 k, a, b, a1, b1 = 2, 4, 1, 12, 4
Moshe Zadka38e083b2001-02-20 16:13:43 +000015 while 1:
16 # Next approximation
Collin Winter6f2df4d2007-07-17 20:59:35 +000017 p, q, k = k*k, 2*k+1, k+1
Moshe Zadka38e083b2001-02-20 16:13:43 +000018 a, b, a1, b1 = a1, b1, p*a+q*a1, p*b+q*b1
19 # Print common digits
Benjamin Petersond7b03282008-09-13 15:58:53 +000020 d, d1 = a//b, a1//b1
Moshe Zadka38e083b2001-02-20 16:13:43 +000021 while d == d1:
22 output(d)
Collin Winter6f2df4d2007-07-17 20:59:35 +000023 a, a1 = 10*(a%b), 10*(a1%b1)
Benjamin Petersond7b03282008-09-13 15:58:53 +000024 d, d1 = a//b, a1//b1
Guido van Rossumec758ea1991-06-04 20:36:54 +000025
Guido van Rossum0b2b4401992-08-31 10:54:17 +000026def output(d):
Moshe Zadka38e083b2001-02-20 16:13:43 +000027 # Use write() to avoid spaces between the digits
28 # Use str() to avoid the 'L'
29 sys.stdout.write(str(d))
30 # Flush so the output is seen immediately
31 sys.stdout.flush()
Guido van Rossum0b2b4401992-08-31 10:54:17 +000032
Johannes Gijsbers7a8c43e2004-09-11 16:34:35 +000033if __name__ == "__main__":
34 main()