-1
print(-2//4)

The output is -1. I do not understand the logic. Why the negative modulo?

Vega
  • 25,886
  • 26
  • 85
  • 95
Dora89
  • 577
  • 1
  • 5
  • 7
  • `(-2) ÷ 4` is `-1 remainder 2`. The remainder has to be between 0 (inclusive) and 4 (exclusive), so this is the only answer that works. – khelwood Jun 19 '20 at 12:56

1 Answers1

1

(-2) ÷ 4 gives -1 remainder 2.

The relation that has to be correct is that for integers a and b

a = (a//b) * b + (a%b)

In this case, b is 4, and the remainder a%b must be between 0 (inclusive) and 4 (exclusive). So the only values for a//b and a%b that work are

a//b = -1
a%b = 2

which gives

-2 = -1 * 4 + 2
a   a//b  b  a%b

TLDR

The precise value of (-2) / 4 is -0.5. The greatest integer not greater than -0.5 is -1.

khelwood
  • 52,115
  • 13
  • 74
  • 94