Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does 1 // 0.1 == 9.0? [duplicate]

In Python 2.7 and 3.x, why does integer division give me a non-correct number when dividing by a number 0 < x < 1?

Negative numbers -1 < x < 0 even work correctly:

>>> 1//.1
9.0
>>> 1//-.1
-10.0

I understand that integer division with a negative (or positive) number rounds toward negative infinity, however I would have thought 1//.1 should result in 10.0 since 1 can be divided by .1 without remainder.

like image 910
Bryce Guinta Avatar asked Oct 01 '16 21:10

Bryce Guinta


1 Answers

What you’re seeing here is essentially the effect of the difference between “normal” division using / and flooring division with //.

What’s also always important to keep in mind is the general issue with floating point arithmetic which is a certain imprecision just because of how they work. In those situations, it’s always good to use the decimal module to check what’s actually going on. So let’s look at what you are doing here:

First of all, .1 is already not precise:

>>> Decimal(.1)
Decimal('0.1000000000000000055511151231257827021181583404541015625')

So, let’s look at the actual result of the divisions:

>>> Decimal(1) / Decimal(.1)
Decimal('9.999999999999999444888487687')
>>> 1 / .1
10.0

As you can see, the normal division using / does not exactly give you 10 with floating point arithmetic. But it’s really close. That’s why, when you use normal floats, you actually get back 10 (since the division imprecision is immediately lost in the imprecision of the number type).

When using flooring division, the result is floored before the imprecision is corrected, so that’s why you get 9:

>>> Decimal(1) // Decimal(.1)
Decimal('9')
>>> 1 / .1
10.0

With negative numbers, the flooring effect is the opposite direction, as explained in that other question:

>>> Decimal(1) / Decimal(-.1)
Decimal('-9.999999999999999444888487687')
>>> 1 / -.1
-10.0
>>> Decimal(1) // Decimal(-.1)
Decimal('-9')
>>> 1 // -.1
-10.0
like image 50
poke Avatar answered Oct 11 '22 20:10

poke