Strange behavior of int()

Rob E remm1 at
Sun Jan 29 18:22:46 CET 2006

> Why is int(r/k), where r = 0.5 and k = 0.5 = 0?  Shouldn't it be 1?
> And why is the last one = 4 and not 5?

I dont' know why the differences in your exact case.  However, please
realise that Regardless of the programming language good programming 
practice is to never rely on the int of a floating point division 
-- or even the int of a floating point constant to be exactly 
the integer value you expect it to be.  This is because both 
constant representations and math operations have rounding 
error.  Instead do less precise conversions by rounding.  For 

    if (a >= 0.0):
       d = int(a+0.5)
       d = int(a-0.5)

If you don't do this sort of thing your programs generally 
are  senstivie to the details of foating point rounding -- 
which is generally dependent on processor, compilier and
in pythons case probably the runtime system.


More information about the Python-list mailing list