5 ms·
I'm having trouble following the negative modulo wording or formula. It says % and %% are identical for unsigned integers then below defines it as a %% b == (
by axaxs 7y ago
I'm having trouble following the negative modulo wording or formula. It says % and %% are identical for unsigned integers then below defines it as
a %% b == ((a % b) + a) % b
If that's the case I can't figure out how they are identical for unsigned integers. Or is that example only a hint for how it would work with negatives?
- klyrs 7y agoI don't precisely follow the text either; it looks like that formula computes ±(2a)%b. Perhaps it's a typo for a %% b == ((a % b) + b) % b Which brings a negative modulus into the range [0, b)
- mjevans 7y agoI think you are probably correct. Lets try a set of simple cases. ( 4 % 3) == 1 ( 4 %% 3) == 1 Are these two correct answers? (-4 % 3) == -2 ?? (-4 %% 3) == 1 ?? Lets assume I got that correct and plug in some numbers. a %% b == (( a % b) + **b** ) % b -4 %% 3 == ((-4 % 3) + 3 ) % 3 -4 %% 3 == (-2 + 3) % 3 -4 %% 3 == 1 However I think it would be clearer for maintenance if the extra operator wasn't used and instead some 'math.absolute()' function were used. PS: Hopefully those are short enough to not die on mobile
- klyrs 7y ago4%3 is 1, so -4%3=-1=3-1=2 (mod 3). I disagree about maintenance: use the right formula and do careful unit testing. Abs isn't a great help here either.
- Vassvik 7y agoIt's definitely a typo. Conceptually I prefer looking at them as a % b = a - trunc(a / b) * b a %% b = a - floor(a / b) * b The latter is even used as % in languages such as Python, which further compounds any syntactical confusion. :D
- gingerBill 7y agoThat was a typo and has now been corrected.