6

I'm confused about the following integer math in python:

-7/3 = -3 since (-3)*3 = -9 < -7. I understand.

7/-3 = -3 I don't get how this is defined. (-3)*(-3) = 9 > 7. In my opinion, it should be -2, because (-3)*(-2) = 6 < 7.

How does this work?

Code-Apprentice
  • 81,660
  • 23
  • 145
  • 268
Jonathan
  • 95
  • 1
  • 5
  • Python generally follows the Principle of Least Astonishment. It just always rounds down for integer division. – Chriszuma Oct 26 '11 at 14:53
  • 3
    Here is the rationale, straight from the bdfl himself: http://python-history.blogspot.com/2010/08/why-pythons-integer-division-floors.html – Björn Lindqvist Oct 26 '11 at 14:56
  • 4
    For people coming here for integer division help: In Python 3, integer division is done using `//`, e.g. `-7 // 3 = -3` but `-7 / 3 = -2.33..`. – poke Oct 26 '11 at 14:57
  • 3
    Btw. mathematically there is no real difference between `-7/3` and `7/-3`, so having two different results would be a bit more complicated. – poke Oct 26 '11 at 15:00
  • 1
    @poke You can use `//` in Python 2 as well. – agf Oct 26 '11 at 15:13
  • To expand on what @poke said; `-7/3` == `7/-3` == `-1 * 7/3` (disregarding rounding here) – Daenyth Oct 26 '11 at 15:26

5 Answers5

14

From the documentation:

For (plain or long) integer division, the result is an integer. The result is always rounded towards minus infinity: 1/2 is 0, (-1)/2 is -1, 1/(-2) is -1, and (-1)/(-2) is 0.

The rounding towards -inf explains the behaviour that you're seeing.

NPE
  • 486,780
  • 108
  • 951
  • 1,012
4

This is how it works:

int(x)/int(y) == math.floor(float(x)/float(y))
robert
  • 33,242
  • 8
  • 53
  • 74
1

/ is used for floating point division // is used for integer division(returns a whole number)

And python rounds the result down

BattleDrum
  • 798
  • 7
  • 13
1

Expanding on the answers from aix and robert.

The best way to think of this is in terms of rounding down (towards minus infinity) the floating point result:

-7/3 = floor(-2.33) = -3

7/-3 = floor(-2.33) = -3

amicitas
  • 13,053
  • 5
  • 38
  • 50
0

Python rounds down. 7/3 = 2 (2+1/3) -7/3 = -3 (-2+1/3)

Rhand
  • 901
  • 7
  • 20