Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Integer division in Python

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?

like image 613
Jonathan Avatar asked Oct 26 '11 14:10

Jonathan


People also ask

What is integer of division?

Integer division is division in which the fractional part (remainder) is discarded is called integer division and is sometimes denoted . Integer division can be defined as , where "/" denotes normal division and is the floor function. For example, so.

How do you divide numbers in Python?

In Python, there are two types of division operators: / : Divides the number on its left by the number on its right and returns a floating point value. // : Divides the number on its left by the number on its right, rounds down the answer, and returns a whole number.

What happens when you do integer division in Python?

In Python, there are two kinds of division: integer division and float division. Integer division returns the floor of the division. That is, the values after the decimal point are discarded. It is written as '//' in Python 3.

How do you divide an integer and int in Python?

In Python 3, integer division (or floor division) uses the double front-slash // operator. In Python 2, integer division uses the single front-slash / operator.


1 Answers

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.

like image 189
NPE Avatar answered Oct 13 '22 21:10

NPE