Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Integer division in Python 3 - strange result with negative number [duplicate]

I am new to Python, and I am learning operators right now. I understood that:

  • The / operator is used for floating point division and
  • // for integer division.

Example:

7//3 = 2

And 7//-3=-3. Why is the answer -3?

I am stuck here.

like image 792
princess Avatar asked Dec 11 '15 07:12

princess


1 Answers

// is not integer division, but floor division:

7/-3  -> -2.33333...
7//-3 -> floor(7/-3) -> floor(-2.33333...) -> -3

PEP 238 on Changing the Division Operator:

The // operator will be available to request floor division unambiguously.

See also Why Python's Integer Division Floors (thanks to @eugene y) - Basically 7//-3 is -7//3, so you want to be able to write:

-7 = 3 * q + r

With q an integer (negative, positive or nul) and r an integer such that 0 <= r < 3. This only works if q = -3:

-7 = 3 * (-3) + 2
like image 118
Holt Avatar answered Oct 27 '22 00:10

Holt