code optimization (calc PI) / Full Code of PI calc in Python and C.

Gabriel Genellina gagsl-py at
Thu Jan 4 02:57:50 CET 2007

At Wednesday 3/1/2007 22:10, Michael M. wrote:

>Ok, here is the code. It is a translation of the following code, found
>on the internet.
>* The C is very fast, Python not.
>* Target: Do optimization, that Python runs nearly like C.

Why? Python is strong in other aspects, *not* on computation speed.

Anyway, for a nice and rather fast Python implementation (yielding 
unlimited digits *without* unlimited storage), see
The code, for reference:

def pi():
      k, a, b, a1, b1 = 2, 4, 1, 12, 4
      while 1:
          # Next approximation
          p, q, k = k*k, 2*k+1, k+1
          a, b, a1, b1 = a1, b1, p*a+q*a1, p*b+q*b1
          # Yield common digits
          d, d1 = a/b, a1/b1
          while d == d1:
              yield str(d)
              a, a1 = 10*(a%b), 10*(a1%b1)
              d, d1 = a/b, a1/b1

import sys

(The converted C code does a lot of nonsense in Python terms - maybe 
you should try to interpret *what* it does and then reimplement that 
using Python)

Gabriel Genellina
Softlab SRL 


Preguntá. Respondé. Descubrí. 
Todo lo que querías saber, y lo que ni imaginabas, 
está en Yahoo! Respuestas (Beta). 
¡Probalo ya! 

More information about the Python-list mailing list