Bryce Guinta - 1 year ago 44

Python Question

In Python

`2.7`

`3.x`

`0 < x < 1`

Negative numbers

`-1 < x < 0`

`>>> 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`

`10.0`

`1`

`.1`

Answer Source

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
```