Leibniz_Pi.py

Bengt Richter bokr at oz.net
Sun Oct 13 00:17:40 CEST 2002


On Sat, 12 Oct 2002 10:01:09 -0500, Skip Montanaro <skip at pobox.com> wrote:

>
>I always get ZeroDivisionError.  It appears that on my machine (Powerbook G4
>running OSX 10.2.1) that time.clock() isn't fine grained enough, so it makes
>a pass of the loop without clock() being able to detect the time difference.
>
Well, I won't repost the whole thing, but try these changes on your machine.

BTW, I once played around with generating binary instead of decimal digits, which you can do
by changing a couple of magic 10's to 2's in the algorithm (and catching the first digit
for special treatment, as it will be 3 either way). Anyway, it provides a stream of bits
that can drive interesting things like dots or turtle tile strokes on graphics. Of course you
can do that with decimals or other bases too (bigger bases need a different lambda for
the digit conversion though). Maybe I'll wrap this in a class with a digit list callback
(like the 50 in this, or other lengths, e.g., 3 might be useful for watching rgb dots one by one).
Just not enough time... 

----------------------------------------------------------------------------
--- pisigint.py.1       Sat Oct 12 00:06:39 2002
+++ pisigint.py Sat Oct 12 15:02:57 2002
@@ -15,6 +15,9 @@
 #
 # See also the ABC Programmer's Handbook, by Geurts, Meertens & Pemberton,
 # published by Prentice-Hall (UK) Ltd., 1990.
+#
+# Original author is not responsible for any errors I may have introduced.
+# Bengt Richter

 import sys, signal
 from time import clock
@@ -34,6 +37,7 @@
 digline = []
 start=clock()
 sys.__stderr__.write('\r(Type Ctrl-C to stop generating pi)\n')
+DT_SMALL = 50.0e-5    # to stay within %8.2f

 while not sh.signaled:
     # Next approximation
@@ -47,7 +51,11 @@
         #sys.__stderr__.write('\r%5d' % (digits,))
         digline.append(d)
         if len(digline)==50:
-            sys.__stderr__.write('\r%5d %8.2f dig/sec  ' % (digits, 50.0/(clock()-start)))
+            delta_t = clock()-start
+            if delta_t < DT_SMALL:
+                sys.__stderr__.write('\r%5d ( many ) dig/sec  ' % digits)
+            else:
+                sys.__stderr__.write('\r%5d %8.2f dig/sec  ' % (digits, 50.0/delta_t))
             lines += 1
             print ''.join(map(lambda x: chr(x+48),digline))
             digline = []
--------------------------------

Regards,
Bengt Richter



More information about the Python-list mailing list