While Statement

Tim Wintle tim.wintle at teamrubber.com
Fri May 22 08:19:36 EDT 2009


On Fri, 2009-05-22 at 13:19 +0200, Andre Engels wrote:
> number/total = 998/999 = 0
> number/total*100 = 0*100 = 0
> float(number/total*100) = float(0) = 0.0
> 
> Change "float(number/total*100)" to "float(number)/total*100" and it
> should work:

I'd use:

 (number * 100.)/total

- works because
 <int> * <float> => <float> 

It's a minor thing, but it's much faster to cast implicitly as you miss
the python function call overhead - it's no extra work to write, and for
numerical things it can really speed things up.

>>> a = timeit.Timer("float(200)/5*100")
>>> b = timeit.Timer("(200*100.)/5")
>>> a.timeit(10000000)
12.282480955123901
>>> b.timeit(10000000)
3.6434230804443359

Tim W





More information about the Python-list mailing list