modulo operator

Q&ACategory: Questionsmodulo operator
Joris Roels asked 4 years ago

The modulo operator returns negative values when a negative input is given. Isn’t it more intuitive that this operator always returns the positive remainder, or is there another reason for this? For example: 
mod(7,5) = 2 % this is fine
mod(-7,5) = -2 % i would expect this to be 3

1 Answers
bgoossen Staff answered 4 years ago

In Quasar, the sign of the result of the mod() function is the same as the sign of the dividend (as in C#, C/C++, Java, …). As such it is actually rather a remainder function than a modulo function.The function that you are looking for here is periodize (periodize(-7,5) = 3 and periodize(7,5) = 2). Periodize is actually defined as follows:

periodize = (n, N) -> (q = mod(n, N); q < 0 ? q + N : q)