I could not understand the difference between these two (mod
& rem
) functions.
Description: mod and rem are generalizations of the modulus and remainder functions respectively. mod performs the operation floor on number and divisor and returns the remainder of the floor operation. rem performs the operation truncate on number and divisor and returns the remainder of the truncate operation.
rem is integer remainder, satisfying: (x `quot` y)*y + (x `rem` y) == x. div is integer division truncated toward negative infinity.
Clojuredoc's example for rem
describes the difference:
;; rem and mod are commonly used to get the remainder.
;; mod means Gaussian mod, so the result is always
;; non-negative. Don't confuse it with ANSI C's %
;; operator, which despite being pronounced
;; 'mod' actually implements rem, i.e. -10 % 3 = -1.
user=> (mod -10 3)
2
user=> (rem -10 3)
-1
mod
returns the difference of the first number, and the biggest integer (possibly negative) multiple of the second number that is less than the first number:rem
is just the remainder.
For example (rem -4 3) => -1
no surprise here: -4 divided by 3 is -1 with -1 "left over".
But weirdness happens if we use mod: (mod -4 3) => 2
:
So even though they usually act similarly, mod does not return the remainder, it does something more specific.
You might find these clojuredocs examples helpful.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With