I was reading C++ Primer 5th. When it comes to % operator, I was puzzled by the result -21%4=-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.
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'sTrue
. 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:
- some rounding towards negative infinity -> (result in)remainder's sign is the same with divisor
- 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.