Compact Python library for math statistics

Andrew Dalke adalke at mindspring.com
Sun Apr 11 18:55:02 EDT 2004


<beliavsky at aol.com>
> My original code, the code with range replaced by xrange, and the code
> with the further replacement of "float(i)" with "i" take 22.0, 20.5,
> and 14.4 seconds. So it looks like removing unnecessary casts can save
> substantial time. Thanks.

The following should be even faster

def sum_sqrt(n):
  sum = 0.0
  for i in xrange(1, n):
    sum = sum + i ** 0.5
  return sum

print sum_sqrt(10000000 + 1)

Local variables have a fast lookup while module variables (that is,
ones outside a function) have to look up the variable in the
module dictionary.

Your code (in module scope) takes 24.5 seconds on my box
while my function version takes 17.5 seconds.

                    Andrew
                    dalke at dalkescientific.com





More information about the Python-list mailing list