[Tutor] Percentage

Jorge Godoy godoy at ieee.org
Mon Nov 7 15:14:03 CET 2005


Frank Moore <francis.moore at rawflow.com> writes:

> Johan,
> 
> You could try:
> 
> percentage = (42 * 250)/100
> 
> This gives the answer 105.

And that sounds weird, doesn't it?  42 is smaller than 250, so I'd expect it
to be less than 100% of the value...  In fact, it is 

>>> 42.0/250
0.16800000000000001
>>> (42.0/250)*100
16.800000000000001
>>> 

I suspect the problem is due to the fact that Python does integer division by
default: 

>>> 42/250
0
>>>

So, how to make it generic?

>>> a = 42
>>> b = 250
>>> a / b
0
>>> float(a)/b
0.16800000000000001
>>> 

One of the members has to be a floating point so that floating point division
is performed instead of integer division.


Be seeing you,
-- 
Jorge Godoy      <godoy at ieee.org>



More information about the Tutor mailing list