Serious error in int() function?

blindanagram at nowhere.net blindanagram at nowhere.net
Wed Apr 13 04:04:25 EDT 2016


On 13/04/2016 08:41, martin.spichty at gmail.com wrote:
> Hi,
> 
> there may be a serious error in python's int() function:
> 
> print int(float(2.8/0.1))
> 
> yields
> 
> 27
> 
> instead of 28!!
> 
> I am using Python Python 2.7.6, GCC 4.8.2 on Linux Ubuntu.
> 
> Is that known?

This arises because finite floating point arithmetic is not exact so
2.8/0.1 results in 27.999999999999996.  And, since the int() function
truncates towards zero, this results in a value of 27.

If you want the nearest integer you should use round(x) rather than int(x).




More information about the Python-list mailing list