What is the purpose of MathUtils.euclideanModulo, and how is it different from a regular modulo?

Viewed 264

I'm a bit confused about the euclideanModulo method of mathutils in threejs. I already know what a modulo symbol does, but the euclideanModulo looks quite different.

( ( n % m ) + m ) % m

I tried looking up the semantics of Euclidean, but it only says this:

relating to or denoting the system of geometry based on the work of Euclid and corresponding to the geometry of ordinary experience.

Can anyone explain this? I can't find a further explaination anywhere?

1 Answers

There's a well-documented Javascript modulo bug that shows up when using negative numbers. You can think of x % 4 as a number wheel:

enter image description here

  • When x goes from 0 into positives, your results are: 0, 1, 2, 3, 0, 1, 2, ....
  • When x goes from 0 into negatives, the results are: 0, 3, 2, 1, 0, 3, 2, ...

But in JavaScript, when you perform -5 % 4 you get -1, which is not the correct answer. It's not even in the list of possible answers. How is it even possible to have a negative remainder?! The answer should be 3. Here's a list of correct answers, vs incorrect Javascript answers:

1 % 4 = 1   // JS gives you 1
0 % 4 = 0   // JS gives you 0
-1 % 4 = 3  // JS gives you -1
-2 % 4 = 2  // JS gives you -2
-3 % 4 = 1  // JS gives you -3
-4 % 4 = 0  // JS gives you -0
-5 % 4 = 3  // JS gives you -1

To make your life easier, Three.js gives you a utility to get the correct answer to circumvent this JavaScript bug. THREE.MathUtils.euclideanModulo(-5, 4) gives you the correct answer 3.

Related