Question

In the CoffeeScript documentation on operators it says that you can use %% for true mathematical modulo, but there is no explanation as to why this is different from the "modulo operator" % in JavaScript.

Further down it says that a %% b in CoffeeScript is equivalent to writing (a % b + b) % b in JavaScript but this seem to produce the same results for most simple cases.

Was it helpful?

Solution

I did find the answer in another StackOverflow question and answer JavaScript % (modulo) gives a negative result for negative numbers and I wanted to share it for people who like me only looked for a "CoffeeScript" related explanations and thus have a hard time finding the correct answer.

The reason for using a %% b which compiles to (a % b + b) % b is that for negative number, like -5 % 3, JavaScript will produce a negative number -5 % 3 = -2 while the correct mathematical answer should be -5 % 3 = 1.

The accepted answer refers to an article on the JavaScript modulo bug which explains it well.

OTHER TIPS

Made no sense for me at first, so I believe it needs an example

check = (a,b) ->
  c = (b*Math.floor(a/b)) + a%b
  d = (b*Math.floor(a/b)) + a%%b
  console.log(
    [c, c == a]
    [d, d == a]
  )

check  78, 33 # [ 78, true ] [ 78, true ]
check -78, 33 # [ -111, false ] [ -78, true ]

###
 78 mod 33 = 12
-78 mod 33 = 21

check:  78 = 33 *  2 + 12
check: -78 = 33 * -3 + 21
###

Looks like modulo is a mathematical trick to be able to use one formula for all numbers instead of one for negatives and second for positives. Don't know if it's more than just a trick and have some intrinsic meaning though.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top