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

Marc 'BlackJack' Rintsch bj_666 at gmx.net
Thu Jan 4 02:46:58 EST 2007


In <cuYmh.201$9v1.239 at nntpserver.swip.net>, Michael M. wrote:

> * The C is very fast, Python not.
> * Target: Do optimization, that Python runs nearly like C.

As someone else already asked: Why?  You can't beat a compiled to machine
code language with an interpreted one when doing integer arithmetic.

> counter=c
> while 0<=counter+4000:
>    f.append(2000)  #   f.append( int(a/5) )
>    counter=counter-1
>    # b=b+1

Why do you count so complicated here?  It's hard to see that this creates
a list with 2801 elements.

>      d = int(d/g)  ## needs cast to int

Instead of converting the numbers to float by "real" division and then
converting back the result you should do integer division:

  d = d // g

or

  d //= g

>    pi = pi + str("%04d" % int(e + d/a))

The `str()` call is unnecessary.  And again: try to stick to integer
arithmetic with ``//``.

Here is my attempt to convert the C code, not written with speed in mind
and I was too lazy too time it.  :-)

from itertools import izip

def pi():
    result = list()
    d = 0
    e = 0
    f = [2000] * 2801
    for c in xrange(2800, 0, -14):
        for b, g in izip(xrange(c, 1, -1), xrange((c * 2) - 1, 0, -2)):
            d += f[b] * 10000
            h, f[b] = divmod(d, g)
            d = h * b
        h, i = divmod(d, 10000)
        result.append('%.4d' % (e + h))
        e = i
    return ''.join(result)

Ciao,
	Marc 'BlackJack' Rintsch



More information about the Python-list mailing list