/Demo/scripts/pi.py

http://unladen-swallow.googlecode.com/ · Python · 34 lines · 16 code · 5 blank · 13 comment · 3 complexity · cd3cc9f0ba4ac6d14dc42c18e9287ac7 MD5 · raw file

  1. #! /usr/bin/env python
  2. # Print digits of pi forever.
  3. #
  4. # The algorithm, using Python's 'long' integers ("bignums"), works
  5. # with continued fractions, and was conceived by Lambert Meertens.
  6. #
  7. # See also the ABC Programmer's Handbook, by Geurts, Meertens & Pemberton,
  8. # published by Prentice-Hall (UK) Ltd., 1990.
  9. import sys
  10. def main():
  11. k, a, b, a1, b1 = 2L, 4L, 1L, 12L, 4L
  12. while 1:
  13. # Next approximation
  14. p, q, k = k*k, 2L*k+1L, k+1L
  15. a, b, a1, b1 = a1, b1, p*a+q*a1, p*b+q*b1
  16. # Print common digits
  17. d, d1 = a//b, a1//b1
  18. while d == d1:
  19. output(d)
  20. a, a1 = 10L*(a%b), 10L*(a1%b1)
  21. d, d1 = a//b, a1//b1
  22. def output(d):
  23. # Use write() to avoid spaces between the digits
  24. # Use str() to avoid the 'L'
  25. sys.stdout.write(str(d))
  26. # Flush so the output is seen immediately
  27. sys.stdout.flush()
  28. if __name__ == "__main__":
  29. main()