11 ms·
Modulo of negative numbers (2011)
- rightbyte 4y agoThe four different integer mod types gives me a headache. I just can't understand them or remember the difference. I solve the problem by never using mod or division for that matter with negative numbers.
- nh23423fefe 4y agoIt's easy to remember if you apply the operation to whole number line instead of trying to remember the cases. There are only 2 cases either you truncate to zero or you floor to negative infinity. The zero behavior breaks the symmetry to help remember. n * truncate(a/n) + rem(a,n) = a n * floor(a/n) + mod(a,n) = a Now suppose that "a" is any real, a/n shared by both. however truncate and floor will do different things to the negatives. truncate "moves" numbers to zero .............................................................. >>.>>.>>.>>.>>.>>.>>.>>.>>.>>0<<.<<.<<.<<.<<.<<.<<.<<.<<.<<.<< while floor "moves" number to -inf .............................................................. <<.<<.<<.<<.<<.<<.<<.<<.<<.<<0<<.<<.<<.<<.<<.<<.<<.<<.<<.<<.<< when we then multiply by n its clear the positive "a" is the same however for negative a floor < truncate and so mod is positive while rem is negative for a < 0 : floor (a/n) < truncate(a/n) unless n divides a then they are = The other case is for negative n, but that just flips the division and multiplication twice which has the effect of changing floor to ceiling and truncate to zero be truncate away from zero which flips the mod sign, but leaves rem alone, because its symmetric about zero.
- Groxx 4y agoThere are only two cases... except when there are four, as the article covers. With wildly different conclusions by different languages, so there is no one interpretation / sane mental model that can be applied. Mod is "fun". I agree, I simply avoid negative numbers entirely, and handle them more explicitly when needed. That way it's language independent.
- StefanKarpinski 4y agoThere are actually as many cases as there are rounding modes, which is seven, and for most of them unlike `mod` and `rem` there's no common name for these remainder operations: - RoundNearest - RoundNearestTiesAway - RoundNearestTiesUp - RoundToZero — rem, div - RoundFromZero - RoundUp - RoundDown — mod, fld (i.e. floor(x/y) but without incorrect corner cases) Most languages have no way of doing most of these, but then again, they're mostly pretty useless. They're really only useful when you're pairing division with a specific kind of rounding with a remainder that needs to match. Example of whacky remainder behavior in the "familiar" RoundNearest mode (default rounding mode for floating point): julia> [k => rem(k, 4, RoundNearest) for k=-6:6] 13-element Vector{Pair{Int64, Int64}}: -6 => 2 -5 => -1 -4 => 0 -3 => 1 -2 => -2 -1 => -1 0 => 0 1 => 1 2 => 2 3 => -1 4 => 0 5 => 1 6 => -2 Wild, huh? Output range for modulus 4 is -2:2 and whether you get -2 or 2 alternates with each cycle around the ring. (Of course, Julia has comprehensive support for all of these because we're a bunch of nerds for this kind of thing.)
- rightbyte 4y ago> rem (3, 4) => -1 Dear God no why?! I thought my confusion around modulus could not get any worse :)
- FabHK 4y agoJulia has functions divrem and fldmod that each return the quotient and remainder, with one or the other convention.
- StefanKarpinski 4y agoThe `rem`, `div` and `divrem` functions also all optionally take a rounding mode argument that lets you have the behavior that matches any rounding mode, where `RoundToZero` matches `div` and `RoundDown` matches `mod`, but there are actually a total of seven rounding modes. Most of them are pretty useless, but if you need some style of division and the remainder to match, this is very helpful.
- michae2 4y agoScheme also distinguishes between the cases using separate remainder and modulo functions. https://www.scheme.com/tspl4/objects.html#./objects:s98 https://www.scheme.com/tspl4/objects.html#./objects:s98
- nayuki 4y agoRust has x.rem_euclid(y), which differs from the % operator. See https://doc.rust-lang.org/std/primitive.i32.html#method.rem_euclid https://doc.rust-lang.org/std/primitive.i32.html#method.rem_... . Full demo: https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=9705937276e71dc9755dc4f0455b097b https://play.rust-lang.org/?version=stable&mode=debug&editio... Haskell has separate mod and rem functions too. Above and below the heading "Even or Odd", the <pre> blocks suffer from "scrollbar blindness" on Windows. https://web.archive.org/web/20200827132812/https://svenkadak.com/blog/scrollbar-blindness https://web.archive.org/web/20200827132812/https://svenkadak...
- orlp 4y agoRust's rem_euclid is still wrong for negative moduli. To see why, remember that we want n = remainder + quotient * divisor. Now look at the horrible mess that is div_euclid: > In other words, the result is self / rhs rounded to the integer q such that self >= q * rhs. If self > 0, this is equal to round towards zero (the default in Rust); if self < 0, this is equal to round towards +/- infinity. Python gets it right. Division is simply flooring division, and modulo is defined to satisfy n = remainder + quotient * divisor. That immediately gets you all the nice behavior such as (-1) % 10 = 9, and 1 % -10 = -9.
- nextaccountic 4y agoCan you clarify why is Rust's div_euclid and rem_euclid are incorrect? For reference, here's what Rust prints for this https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=a0ff242df33a7d411f803cd06cd04f40 https://play.rust-lang.org/?version=stable&mode=debug&editio... fn main() { dbg!(1_i32.rem_euclid(-10)); dbg!(-1_i32.rem_euclid(10)); } [src/main.rs:2] 1_i32.rem_euclid(-10) = 1 [src/main.rs:3] -1_i32.rem_euclid(10) = -1 I found only this issue https://github.com/rust-lang/rust/issues/87970 https://github.com/rust-lang/rust/issues/87970 but has no details Here's the discussion that lead to the implementation of those functions, from more recent to least recent, * the tracking issue https://github.com/rust-lang/rust/issues/49048 https://github.com/rust-lang/rust/issues/49048 * the RFC https://github.com/rust-lang/rfcs/pull/2169 https://github.com/rust-lang/rfcs/pull/2169 * the internals discussion https://internals.rust-lang.org/t/mathematical-modulo-operator/5952 https://internals.rust-lang.org/t/mathematical-modulo-operat... It's baffling that Rust got this wrong..
- hyperthesis 4y agoI've been using this style, in TFA as ((a % b) + b) % b It feels like there should be a nicer way (apart from the conditional one), but I can't think of it. Can you prove there isn't one?
- layer8 4y agoJust as a caveat, ((a % b) + b) can overflow. For example, with 32-bit signed integer arithmetic, mod(1000000000, 2000000000) using that formula will yield -1294967296 instead of 1000000000.
- klabb3 4y agoIt may also be expensive, since % has the cost of division, and there are two of them..
- wolfi1 4y ago-2 and 1 are mod 3 essentially the same. I don't see here the problem except of course someone didn't expect this result and used it for indexing
- qsort 4y agoSure, but then why if: -13 \equiv 5 \pmod 3 it is the case that: > -13 % 3 === 5 % 3 false I think it's better to use a convention where for all a, b, m, if a and b are congruent mod m, then a%m === b%m
- bajsejohannes 4y agoBut 13 is also equivalent to -2 and 1, mod 3. Why are you doing the modulo operation in the first place? From a mathematical standpoint, I've never seen a use for returning -2 here. I want something unique for the group, so I can ask e.g. `x mod 3 == y mod 3` and have it work regardless of whether x or/and y are negative.
- jhncls 4y agoYour safest bet would be `(x - y) mod 3 == 0`. Of course, that doesn't solve the case when you want to bin the values.
- whoomp12342 4y agowhy would we have any different behavior from division? seems like some languages got it wrong
- rurban 4y agoperl started this bizarre interpretation of mod, some followed. The rest stayed with the POSIX libc definition.
- kevin_thibedeau 4y agoAda had both before Perl existed.
- gerikson 4y agoAccording to the Wikipedia page (linked in the article), Perl uses the floored definition of mod, which is promoted by Knuth, and also used by APL, Fortran and Common Lisp. https://en.wikipedia.org/wiki/Modulo https://en.wikipedia.org/wiki/Modulo
- alphazard 4y agoThis is mostly just an issue of calling what is really a remainder operator "mod". The clearest solution is to disambiguate the two as Zig does.
- Aardwolf 4y agoThe one that returns a negative value for negative first argument has never done anything useful for me, and always made things that are actually useful harder to do. The only useful behavior is that crossing 0 does not change the pattern. Change my mind.
- ajuc 4y agoSame. Imagine we defined substraction in a way that requires almost all the users to check if arguments are positive. It's insane.
- plasticeagle 4y agoI know this is a typo, but I'm imagining that substraction is a form of abstraction where you take things away to make them simpler to understand.
- jjgreen 4y agoLikewise, but I was thinking of extraction of something from beneath something else, probably a mining term ...
- nh23423fefe 4y agoI could imagine 2 use cases divMod is for when you want Z_n, you actually care about the equivalence classes and their "canonical" representative. quotRem is for symmetry. The values of the remainders are the same, but you get some sign flip for free if you want it. So for example. Suppose you had some number of hours and you wanted to "convert to days", if you want symmetric outputs then quotRem will do that and divMod won't. 36 hours divMod 24(hours/day) = 1d + 12h -36 hours divMod 24(hours/day) = -2d + 12h 36 hours quotRem 24(hours/day) = 1d + 12h -36 hours quotRem 24(hours/day) = -1d - 12h obviously the information is the same. 12 = -12 (mod 24) but the form is different.
- Chinjut 4y agoWhen do you ever want that symmetry?