Guido van Rossum | ec758ea | 1991-06-04 20:36:54 +0000 | [diff] [blame^] | 1 | #! /usr/local/python |
| 2 | |
| 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 | |
| 11 | import sys |
| 12 | |
| 13 | def main(): |
| 14 | k, a, b, a1, b1 = 2l, 4l, 1l, 12l, 4l |
| 15 | while 1: |
| 16 | # Next approximation |
| 17 | p, q, k = k*k, 2l*k+1l, k+1l |
| 18 | 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 |
| 21 | #print a, b, a1, b1 |
| 22 | while d = d1: |
| 23 | # Use write() to avoid spaces between the digits |
| 24 | sys.stdout.write(`int(d)`) |
| 25 | # Flush so the output is seen immediately |
| 26 | sys.stdout.flush() |
| 27 | a, a1 = 10l*(a%b), 10l*(a1%b1) |
| 28 | d, d1 = a/b, a1/b1 |
| 29 | |
| 30 | main() |