iordanis
iordanis

Reputation: 1284

python integer division with a float < 1 yields strange result

To illustrate my example

Try running:

print(1//0.1)
print(1/0.1)
print(int(1/0.1))

Output:

>>> print(1//0.1)
9.0
>>> print(1/0.1)
10.0
>>> print(int(1/0.1))
10

The result of 1//0.1 is both not an integer, and incorrect. The same applies with other numbers / test-cases. Is this behavior documented anywhere in python? I could not find anything relevant.

Upvotes: 3

Views: 287

Answers (1)

a_guest
a_guest

Reputation: 36249

It's actually called __floordiv__ according to the data model. The docs for divmod mention the relation to math.floor:

[...] For floating point numbers the result is (q, a % b), where q is usually math.floor(a / b) but may be 1 less than that. In any case q * b + a % b is very close to a, [...]

Hence, if q, r = divmod(a, b) then it holds that q*b + r == a and q == a//b.

>>> a, b = 1, 0.1
>>> q, r = divmod(a, b)
>>> q*b + r == a
True
>>> a//b == q
True

So the only guarantee here is that q*b + r == a holds.


As for 1.0 // 0.1 yielding 9.0 it is because FP numbers are represented internally in base 2, and 0.1 is not a "round" number, but actually, larger than the "mathematical 0.1":

In [79]: f"{0.1:.20f}"
Out[79]: '0.10000000000000000555'

Upvotes: 7

Related Questions