Java – is there any reason why languages allow negative modulus?
I'm curious that these languages (Java, C...) ignore the mathematical definition of modular operation
What does it mean to return a negative value in a module operation (by definition, a positive number should be returned)?
Solution
I suspect that the remaining operators are deliberately designed to have these semantics, and I agree that they are not very useful (will you write a calendar program to display the date before the time of Sunday, anti Saturday, anti Friday,..., anti Monday?)
On the contrary, negative remainder is a side effect of defining integer division
A rem B := A - (A div B) * B
If a div B is defined as TRUNC (A / b), you can get the% operator of C If a div B is defined as floor (A / b), you can get Python's% operator Other definitions are possible
So the real question is:
Why do C, Java, c# etc. use truncated integer division?
Because this is the way of C
Why does C use truncation segmentation?
Initially, C did not specify / should handle negative numbers It left it to the hardware
In practice, every important C implementation uses truncation, so in 1999, these semantics officially became part of the C standard
Why does the hardware use truncation partitioning?
Because it is easier to implement in unsigned partition (= cheaper) If (a < 0) XOR (b < 0), only ABS (a) div ABS (b) is calculated and the symbol is flipped If the remaining part is zero, the flooring department will subtract 1.5% from the quotient for additional steps