Strange division results in python 3

241 views Asked by At

I think there is some inconsistency in the division operation, but I am not sure.

In the following code I would expect either a//c to be 100.0, or b//c to be -99.0.

a = 1.0
b = -1.0
c = 0.01

print (a/c)
print (a//c)
print (b/c)
print (b//c)

gives:

100.0
99.0
-100.0
-100.0

Thanks

1

There are 1 answers

2
Simeon Visser On

This is due to the way floating point numbers are represented. It's not true that 1.0 is exactly 100 times 0.01 (as far as floating points are represented internally). The operator // performs division and floors the result so it may be that internally the number is slightly less than 100.0 and this leads it to being floored to 99.0.

Furthermore, Python 3.x uses a different approach to showing you the floating point number as compared to Python 2.x. This means the result of 1.0 / 0.01, although internally slightly less than 100.0, will be displayed to you as 100.0 because the algorithm determined that the number is close enough to 100.0 to be considered equal to 100.0. This is why 1.0 / 0.01 is shown to you as 100.0 even though this may not be represented internally as exactly that number.