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?

6
  • Python generally follows the Principle of Least Astonishment. It just always rounds down for integer division. Commented Oct 26, 2011 at 14:53
  • 3
    Here is the rationale, straight from the bdfl himself: python-history.blogspot.com/2010/08/… Commented Oct 26, 2011 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... Commented Oct 26, 2011 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. Commented Oct 26, 2011 at 15:00
  • 1
    @poke You can use // in Python 2 as well. Commented Oct 26, 2011 at 15:13

5 Answers 5

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.

Sign up to request clarification or add additional context in comments.

Comments

4

This is how it works:

int(x)/int(y) == math.floor(float(x)/float(y))

Comments

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

Comments

1

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

And python rounds the result down

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.