0

I was reading C++ Primer 5th. When it comes to % operator, I was puzzled by the result -21%4=-1.

  1. At first, I did some research and found that what we commonly use is Euclidean division in Number Theory, which requires remainder r>0. So neither of Python and C++ is implemented in that way. They use something else and that's fine as long as the quotient and remainder are unique.

  2. Then I found out that in python2.7 -21/4=-6 while -(21/4)=-5, -21/4==-(21/4) //False, but in python3 it gives float numbers without rounding so it's True. So I noticed that py2.7 is rounding towards negative infinity while C++ is rounding towards 0. Then I came up this deduction:

    We have int -> need rounding rules when it can't divide exactly:

    1. some rounding towards negative infinity -> (result in)remainder's sign is the same with divisor
    2. some rounding towards zero -> (result in)r's sign is the same with dividend

So I think it is the different rounding rules cause the different result of remainder, is it true? And if it's true, then why we would have the rounding towards negative infinity design at first? (Because it would cause the problem of -21/4==-(21/4) //False). Is it a somehow historical problem or sth else?

I don't think it's a duplicated question. I've read the old post. But it seems the cause and effect is that the rounding rules decides the different result and I am asking if it is true. And why python2.7 rounds towards negative infinity coz I think it's a bad choice.

Rick
  • 7,007
  • 2
  • 49
  • 79
  • @Jarod42 ya, sorry, mistyping. – Rick Nov 09 '17 at 10:13
  • @LưuVĩnhPhúc I've read this already. But I think some answers are wrong about so-called 'true' modulo operation and I wanna know if there's cause and effect between the rounding rules and different remainder result. – Rick Nov 09 '17 at 10:15

1 Answers1

0

Prior to C++11 the behavior of the remainder operator % was implementation defined if one of the arguments was negative.

Since then, the result must be closest negative number possible to zero if the first argument is negative.

The mathematical cousin - the modulus - would set -21 modulo 4 to be 3. What the C++ standard insists is that the mathematical result has 4 subtracted from it to return the required negative.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483