Skip to content

Remainder operator vs. modulo operator

Ekadagami edited this page Feb 6, 2023 · 7 revisions

The diffScript function makes extensive use of the modulo operator. Unfortunately, the »%« in JavaScript is not a true modulo operator, but simply returns the remainder of a division.

  • JavaScript‘s % operator is a remainder operator.
  • Python’s % operator is a modulo operator.

The difference is especially noticeable with negative values for the divisor:

mod 3 mod -3 rem 3 rem -3
-3 0 0 0 0
-2 1 -2 -2 -2
-1 2 -1 -1 -1
0 0 0 0 0
1 1 -2 1 1
2 2 -1 2 2
3 0 0 0 0

For this reason, a separate function for the modulo operator was implemented in Undoh:

static #modulo(n: number, d: number): number { return ((n % d) + d) % d; }

Since the modulo function is used extensively inside the diff function, the Javascript modulo function was replaced by a Webassembly version on January 28. The pseudo code for the modulo function looks like this:

(module (func $modulo (param $n i32) (param $d i32) (result i32) (i32.rem_s (local.get $n) (local.get $d)) (i32.add (local.get $d)) (i32.rem_s (local.get $d)) ) (export "modulo" (func 0)) )

More detailed information on the topic can be found here:

Wikipedia Modulo Operation


And this is what OpenAI ChatGPT has to say about the topic:

The remainder operator, denoted by the % symbol in most programming languages, returns the remainder of a division operation. For example, the expression 10 % 3 would evaluate to 1, because 10 divided by 3 is 3 with a remainder of 1.

The modulo operator, on the other hand, is a mathematical concept that is not always directly represented by a symbol in programming languages. In some languages, the modulo operator is the same as the remainder operator, but in other languages, it may be a different operator or even have no direct equivalent.

The main difference between the remainder and modulo operators is that the remainder operator always returns a result with the same sign as the dividend (the number being divided), while the modulo operator always returns a non-negative result. For example, the expression -10 % 3 would evaluate to -1 using the remainder operator, but the same expression would evaluate to 2 using the modulo operator, since -10 modulo 3 is the same as -10 divided by 3 with a remainder of 2.

In general, the modulo operator is more versatile and has more applications in mathematical and computational settings, while the remainder operator is more commonly used in programming languages for basic arithmetic operations.

Clone this wiki locally