209 points · by tosh · 4y ago · 169 comments
>>> 10%3
1
>>> (-10)%3
2
>>> 10%(-3)
-2
>>> (-10)%(-3)
-1(well a report in TOPLAS really, but that's pretty close)
There are technically 5 different versions of this operation, though only 2 (possibly 3) are in common use. Common Lisp seems to implement all of them except, somewhat oddly, the euclidean version (the "actual modulo"), its mod function is instead a flooring division.
edit: it looks like Python also follows flooring, not euclidean, meaning the quotient is rounded downwards, and per "a = nq + r" the remainder has the sign of the divisor:
>>> 5 % -2
-1
>>> divmod(5, -2)
(-3, -1)
The C version is the "truncating" division, meaning the quotient is truncated (rounded towards 0).https://stdlib.ponylang.io/builtin-Integer/#div_unsafe
and, in Ponylang, i/0 usually results in 0.
After thinking about this, what I really want is a way to access an array with an unadjusted number and tell the array to do whatever modulizing is necessary. e.g. instead of
a[small]
a[mod1(big)]
I'd like to have something more like a{small}
a[big]Why? Mathematically, dividing two integers yields a real. If you want the result to be an integer, you need to define some rounding operation on the real result to produce an integer.
That is the source of the divergence between C and Python here, C rounds by truncation (towards 0), Python rounds by flooring (towards -inf).
> The binary arithmetic operators are +, -, *, /, and the modulus operator %.
https://archive.org/details/TheCProgrammingLanguageFirstEdit...
At least, that was the C reference I used in college.
The draft version "X3.???-1988" at https://web.archive.org/web/20161223125339/http://flash-gord... (linked-to from Wikipedia) has:
> % modulus operator: 3.3.5
which seems off to a good start for K&R, but then also has:
> remainder operator, %, 3.3.5
and 3.3.5 says "the result of the % operator is the remainder" -- not a whiff of a modulus present there.
Thanks!
You will find "modulus operator" to refer to % in C in all of the above (other than the standard).
It goes on to say: "x % y produces the remainder when x is divided by y" and that "the sign of the result for % are machine-dependent for negative operands, as is the action taken on overflow or underflow".
The binary operator / indicates division. When positive integers are divided, truncation is toward 0, but the form of truncation is machine-dependent if either operand is negative. On all machines covered by this manual, the remainder has the same sign as the dividend. It is always true that (a/b)*b + a%b is equal to a (if b is not 0). The binary % operator yields the remainder from division of the first operand by the second.
Are C programmers still using C89 and C90?
The C compilers supplied by microcontroller vendors in particular are often, to put it charitably, not great at conforming with the latest standards.
Postgres only updated to C99 with PG12
https://www.postgresql.org/docs/11/source-conventions.html https://www.postgresql.org/docs/12/source-conventions.html
Some blame to be had by MSVC, which is called out in PEP7: https://www.python.org/dev/peps/pep-0007/#c-dialect
That just makes C look worse. Remainders are always nonnegative, as specified in the Division Algorithm [note that the Division Algorithm is the name of a theorem, not an algorithm].
https://en.wikipedia.org/wiki/Euclidean_division
Also, I'm not aware of a definition of "modulo" other than "remainder". Where are you getting the idea that they're different?
For example, https://en.wikipedia.org/wiki/Modulo_operation explicitly defines "modulo" as "remainder".
> a mod b = ((a % b) + b) % b
The first remainder bounds it to -b < x < b. Then adding b goes to 0 < x < 2b. Then the second remainder gets th desired 0 <= x < b.
This will not work for b > max_int / 2 (solution in that case is much mkre language dependent)
mod is Python's %, rem is C's %.
Having this for unsigned types allows you to write rem_euclid() if that's definitely what you meant even when you aren't sure if the type you'll be using here will be signed (and thus it matters) or not.
Unfortunately Rust's std::ops::Rem trait (the trait which provides the overloadable % operator) does not offer this alternative, so if all you know about a type is that you can apply the modulus operator to it, you only get that operator and there's no uniform way to get a Euclidean remainder instead.
Scheme:
> (mod 5 2)
1
> (mod 5 -2)
1
> (mod -5 2)
1
> (mod -5 -2)
1
> (remainder 5 2)
1
> (remainder 5 -2)
1
> (remainder -5 2)
-1
> (remainder -5 -2)
-1
Haskell: Prelude> a = 5 :: Integer
Prelude> b = 2 :: Integer
Prelude> mod a b
1
Prelude> mod a (-b)
-1
Prelude> mod (-a) b
1
Prelude> mod (-a) (-b)
-1
Prelude> rem a b
1
Prelude> rem a (-b)
1
Prelude> rem (-a) b
-1
Prelude> rem (-a) (-b)
-1
So in Scheme mod is the Euclidean modulus (always >= 0) and remainder takes the sign of the dividend (comes from truncated division, same as C's %). In Haskell mod takes the sign of the divisor (floored division, same as Python), while rem behaves the same way as Scheme's remainder or C's %.I prefer Scheme's way, because it was what we always used in classes when I studied maths. mod returning a negative number is just too weird.
EDIT: It appears that Scheme also has modulo, which comes from floored division:
> (modulo 5 2)
1
> (modulo 5 -2)
-1
> (modulo -5 2)
1
> (modulo -5 -2)
-1https://wiki.forth-ev.de/doku.php/projects:signed_integer_di...
Lots of other languages got it wrong:
https://en.wikipedia.org/wiki/Modulo_operation#In_programmin...
Symmetric division is the kind of thing that causes rockets ships to explode unexpectedly.
Symmetric division considered harmful:
https://www.nimblemachines.com/symmetric-division-considered...
>Since its 1983 standard (Forth-83), Forth has implemented floored division as standard. Interestingly, almost all processor architectures natively implement symmetric division.
>What is the difference between the two types? In floored division, the quotient is truncated toward minus infinity (remember, this is integer division we’re talking about). In symmetric division, the quotient is truncated toward zero, which means that depending on the sign of the dividend, the quotient can be truncated in different directions. This is the source of its evil.
>I’ve thought about this a lot and have come to the conclusion that symmetric division should be considered harmful.
>There are two reasons that I think this: symmetric division yields results different from arithmetic right shifts (which floor), and both the quotient and remainder have singularities around zero.
>If you’re interested in the (gory) details, read on. [...]
"The expression x % y produces the remainder when x is divided by y" K&R C p37
r = (i + N) % N
which handles cases where i >= -N which is mostly what I run into when i is negative.I remember Ada having two different operators REM and MOD which I think is the best language choice.
Nitpick: it never was “just do whatever the underlying hardware does”. C standards try hard to avoid mentioning hardware at all (and, as far as I know, succeed at that), and there’s plenty of hardware that doesn’t do mod in hardware, yet supports it in C.
For example, the size of int is not specified by the standard, as you said. But it can still be different from the natural word size of the underlying hardware, if the compiler vendor chooses to make it so. Case in point is int on 64-bit platforms is usually 32-bit in practice. In Microsoft's compiler, even long int is 32-bit even on 64-bit hardware.
I wouldn't even bother with this, I'd just use a modular type (i.e. unsigned).
with Ada.Text_IO;
procedure Main is
-- Modular type (unsigned) which can take values of [0, 15].
type Nibble is mod 16;
Value : Nibble := 0;
begin
-- Prints 0 3 6 9 12 15 2 5 8 11 14 1 4 7 10 13 ...
for I in 0 .. 63 loop
Ada.Text_IO.Put_Line (Value'Image);
Value := Value + 3;
end loop;
end Main;
Then make that type the index into my circular buffer and then I never need to worry about it. type Circular_Buffer is array (Nibble) of Integer;
Buffer : Circular_Buffer;Source: The draft C99 standard http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1256.pdf PDF page 94, physical page 82.
Yes, as someone who both gets open source bug reports and has sent out open source bug reports, what determines whether a behavior being looked at is a bug depends on what the relevant standards say.
https://port70.net/~nsz/c/c89/c89-draft.html#3.3.5
> When integers are divided and the division is inexact, if both operands are positive the result of the / operator is the largest integer less than the algebraic quotient and the result of the % operator is positive. If either operand is negative, whether the result of the / operator is the largest integer less than the algebraic quotient or the smallest integer greater than the algebraic quotient is implementation-defined, as is the sign of the result of the % operator. If the quotient a/b is representable, the expression (a/b)*b + a%b shall equal a .
C99 draft standard: http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1256.pdf PDF page 94, physical page 82, “When integers are divided, the result of the / operator is the algebraic quotient with any fractional part discarded.” with a footnote: “This is often called ‘‘truncation toward zero’’”
I wish % was a modulo instead of a remainder operation; this bug has bitten me more than once.
According to Boute 1992,
> The Ada Reference Manual complements integer division (/) with two functions mod and rem. The first of these violates the division rule
so it doesn't so much have two different operators as one operator and one broken mess, and its one operator is the truncating division (C-style).
Also a quick check of the Hyperspec (or, again, Boute 1992) shows there are not two but 4 definitions based on rounding quotients, I think none of which "always returns a positive number" (which Python also does not do, incidentally).
There is a 5th definition, which Boute 1992 champions, for which the property asserted in the title holds.
r = ((i % N) + N) % N
There may be faster ways, but that should at least be correct for all inputs.
If defined as
```
int16_t mod(int16_t i, int16_t N) {
return ((i % N) + N) % N;
}```
There do not seem to be any issues all the way up to INT16_MAX. Even with negative values of N, it produces the same value as python does (although I am not certain I understand what modulus means with a negative N)
Taken from Modula-2.
The RFC that introduced rem_euclid: https://github.com/rust-lang/rfcs/blob/master/text/2169-eucl...
For what it's worth, Python does not implement euclidean modulo (it implements flooring division aka "F-definition", proposed by Knuth), so Rust did not implement "this" it implemented an operation which, as far as I can tell, Python doesn't have.
It seems quite relevant as it diverges significantly from the assertion put forth in the tweet: Python's remainder takes the sign of the divisor. So flooring division fixes the more common issue but leaves an other one present.
remainder(a, b)
n = round(a/b)
return a - n * b
Because it rounds to get n, n * b can be greater than a :DEven more fun as the original x87 implementation preceded IEEE754 its remainder operation (fprem, because it's technically a partial remainder) used truncation rather than rounding as that's the obvious behaviour. To support the IEEE754 specification they had to add fprem1 which performs a rounding operation instead. Hurrah! :D
[0] https://github.com/mike-bourgeous/mb-sound/blob/a8eb1232ae35...
If the quotient a/b is representable, the expression (a/b)*b + a%b shall equal a
For division:
The result of the / operator is the quotient from the division of the first operand by the second
Which is remarkably vague. Presumably, they are doing the kind of third grade math where we get a quotient and a remainder (Euclidean division). So, 1/3 is 0, 2/3 is 0, 3/3 is 1, 4/3 is 1, 5/3 is 1, 6/3 is 2, etc.
That in mind, let’s look at -1 % 3 (is 2 when doing a proper modulo operation)
With integers:
(-1 / 3) is 0 (1 / 3 is “0 remainder 1” and multiplied by -1 still gives us 0)
This in mind, the modulo (-1 % 3) needs to give us -1:
(0 * 3) + -1 = -1
So a%b is negative here.
There are some ways to work around this and get a proper modulo.
One common case is to get something modulo a power of 2. This will give us a modulo, 20 in this case, as per the C standard:
#include <stdint.h>
uint32_t foo = 12;
printf("%d\n",-foo % 32);
The reason is because, as per PDF page 55 (page 43) of that draft C99 standard:if the new type is unsigned, the value is converted by repeatedly adding or subtracting one more than the maximum value that can be represented in the new type until the value is in the range of the new type.
So, since foo is unsigned, and a 32-bit int, -foo is -12 + 4294967296, or 4294967284. 4294967284 % 32 as per the spec above is 20, i.e. -12 mod 32.
This trick only works if we modulo a number by a power of 2.
Yes, I have used this trick when writing “golfed” C code which needs to do a circular rotate:
uint32_t r=12,g=1;g=g>>r|g<<-r%32;Unfortunately hardware never fixed this issue, and C is never going to expose an operator that doesn't map primitively to the hardware, so it became the established default.
It also desirable to have the remainder consistent with the result of division, such that x = d*r + mod, where r is the result of division. Combine that with the above requires negative mods.
Consider x/3=y. For real numbers, it's trivial to manipulate this equation into (x-3)/3=y-1. However, this only works when integer division rounds down.
5/3 = 1 rem 2 or 1 rem 2
4/3 = 1 rem 1 or 1 rem 1
3/3 = 1 rem 0 or 1 rem 0
2/3 = 0 rem 2 or 0 rem 2
1/3 = 0 rem 1 or 0 rem 1
0/3 = 0 rem 0 or 0 rem 0
-1/3 = -1 rem 2 or 0 rem -1
-2/3 = -1 rem 1 or 0 rem -2
-3/3 = -1 rem 0 or -1 rem 0
One of these has a consistent pattern, the other doesn't.All of this is a fairly moot point: The answer is it should do what the algorithm using it needs it to do.
[1] e.g. http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1256.pdf PDF page 94/physical page 82
From PDF page 94 (physical page 82) of the draft C99 standard: [1] The result of the / operator is the quotient from the division of the first operand by the second
This is a little vague; it would be better if they called it the “quotient from Euclidean division” (EDIT: This was incorrect. Actually, it’s the quotient from algebraic division, with the fraction truncated, also called “truncation towards zero”. See discussion below.), which is well defined as being -3 in the above example; see https://en.wikipedia.org/wiki/Euclidean_division (EDIT: Euclidean is -4; truncation towards 0 is -3)
[1] http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1256.pdf
In practice, this offloads the problem to your programmer in at least every other case (i.e. when % doesn’t what they need out of box), who then miscalculates or mistests their solution and now the problem is yours.
It doesn’t matter what the standard says, there should be many functions, each for a combination of signs (or roundings) you want in the results. Because your library doesn’t suck and your programmer has things to do instead of fiddling with off by ones and other primitive but highly error-prone-under-stress bs.
main() { printf("%d\n",-7/2);}
Let’s look at, oh, C11: http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdfPDF page 110, physical page 92: When integers are divided, the result of the / operator is the algebraic quotient with any fractional part discarded. with a footnote: This is often called ‘‘truncation toward zero’’
-7/2 is -3.5, so discarding the fractional part gives us -3
-4 also makes sense.
> It also desirable to have the remainder consistent with the result of division, such that x = d*r + mod, where r is the result of division. Combine that with the above requires negative mods.
Python's behaviour is consistent with that definition:
>>> divmod(-7, 2)
(-4, 1)
-7 = -4 * 2 + 1"If both operands are nonnegative then the remainder is nonnegative; if not, the sign of the remainder is implementation-defined"
Fortunately, this was changed at some point between C '99 and C '11, so that now the remainder is consistently defined across all implementations.
$ perl -E 'say(4 % -3)'
-2
$ perl -E 'use integer;say(4 % -3)'
1It's a pattern in Perl, like "use strict;" for example, which is also lexically scoped and has a "no strict;" counterpart.
https://en.cppreference.com/w/cpp/numeric/math/fmod
https://en.cppreference.com/w/cpp/numeric/math/remainder
A valid use may be when approximating a periodic function via a polynomial (e.g. sin/cos), where you will want to first perform range reduction like std::fmod(x, 2 * pi).
As Carmack notes it's great for array/buffer indices - and bites you if you expect it in C!
It was quite confusing trying to port this diff algorithm https://blog.robertelder.org/diff-algorithm/
mouse cursor moves toward up-arrow