Guido van Rossum | f06ee5f | 1996-11-27 19:52:01 +0000 | [diff] [blame] | 1 | #! /usr/bin/env python |
Guido van Rossum | ec758ea | 1991-06-04 20:36:54 +0000 | [diff] [blame] | 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(): |
Collin Winter | 6f2df4d | 2007-07-17 20:59:35 +0000 | [diff] [blame^] | 14 | k, a, b, a1, b1 = 2, 4, 1, 12, 4 |
Moshe Zadka | 38e083b | 2001-02-20 16:13:43 +0000 | [diff] [blame] | 15 | while 1: |
| 16 | # Next approximation |
Collin Winter | 6f2df4d | 2007-07-17 20:59:35 +0000 | [diff] [blame^] | 17 | p, q, k = k*k, 2*k+1, k+1 |
Moshe Zadka | 38e083b | 2001-02-20 16:13:43 +0000 | [diff] [blame] | 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 | while d == d1: |
| 22 | output(d) |
Collin Winter | 6f2df4d | 2007-07-17 20:59:35 +0000 | [diff] [blame^] | 23 | a, a1 = 10*(a%b), 10*(a1%b1) |
Moshe Zadka | 38e083b | 2001-02-20 16:13:43 +0000 | [diff] [blame] | 24 | d, d1 = a/b, a1/b1 |
Guido van Rossum | ec758ea | 1991-06-04 20:36:54 +0000 | [diff] [blame] | 25 | |
Guido van Rossum | 0b2b440 | 1992-08-31 10:54:17 +0000 | [diff] [blame] | 26 | def output(d): |
Moshe Zadka | 38e083b | 2001-02-20 16:13:43 +0000 | [diff] [blame] | 27 | # 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 Rossum | 0b2b440 | 1992-08-31 10:54:17 +0000 | [diff] [blame] | 32 | |
Johannes Gijsbers | 7a8c43e | 2004-09-11 16:34:35 +0000 | [diff] [blame] | 33 | if __name__ == "__main__": |
| 34 | main() |