blob: e73e7eccd4bf961b2fecfe2b6a033c38bfbbf717 [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():
Guido van Rossum0b2b4401992-08-31 10:54:17 +000014 k, a, b, a1, b1 = 2L, 4L, 1L, 12L, 4L
Guido van Rossumec758ea1991-06-04 20:36:54 +000015 while 1:
16 # Next approximation
Guido van Rossum0b2b4401992-08-31 10:54:17 +000017 p, q, k = k*k, 2L*k+1L, k+1L
Guido van Rossumec758ea1991-06-04 20:36:54 +000018 a, b, a1, b1 = a1, b1, p*a+q*a1, p*b+q*b1
19 # Print common digits
20 d, d1 = a/b, a1/b1
Guido van Rossumbdfcfcc1992-01-01 19:35:13 +000021 while d == d1:
Guido van Rossum0b2b4401992-08-31 10:54:17 +000022 output(d)
23 a, a1 = 10L*(a%b), 10L*(a1%b1)
Guido van Rossumec758ea1991-06-04 20:36:54 +000024 d, d1 = a/b, a1/b1
25
Guido van Rossum0b2b4401992-08-31 10:54:17 +000026def output(d):
27 # Use write() to avoid spaces between the digits
28 # Use int(d) to avoid a trailing L after each digit
29 sys.stdout.write(`int(d)`)
30 # Flush so the output is seen immediately
31 sys.stdout.flush()
32
Guido van Rossumec758ea1991-06-04 20:36:54 +000033main()