Serious error in int() function?

Gregory Ewing greg.ewing at canterbury.ac.nz
Wed Apr 13 07:51:26 EDT 2016


martin.spichty at gmail.com wrote:
> print int(float(2.8/0.1))
> 
> yields
> 
> 27
> 
> instead of 28!!

This is a consequence of the fact that the machine does
floating point arithmetic in binary, not decimal.

0.1 is not exactly representable as a binary floating
point number, and the result of the division comes out
very slightly less that 28:

 >>> 2.8/0.1
27.999999999999996

This is not unique to Python; you'll get the same
result from anything that uses the machine's native
floating point numbers.

When using floating point, you always need to be
prepared for slight inaccuracies. Usually you don't
notice them, because the results are rounded to some
reasonable number of decimal places before display.
But sometimes they show up, such as when using
int(), which truncates instead of rounding.

The best way to handle things like this depends on
the circumstances. If you tell us what you're trying
to achieve, we may be able to offer advice.

-- 
Greg



More information about the Python-list mailing list