Better mod function documentation

Issue #722 new
Mihai Ionescu created an issue

Original description:

mod(-1,360) = -1

shouldn't it be 359? why doesn't it map in range [0,360) ?

this works though:

modc(x;c) = x - floor(x/c)*c

speedcrunch 0.12 win7 64bit

Comments (10)

  1. Pol Welter

    Because -1 ≡ 359 (mod 360). Both results are equally valid. Negative numbers in mod operations are not implemented the same across various programming languages. See this wiki page. SpeedCrunch follows the most common approach.

    Still, this should be in the documentation, so I am leaving the issue open.

  2. Tey'

    This is common problem in C/C++ for instance, where each compilers produce different results for the modulo operator when the signs of divisor and dividend are different. As @polwel wrote, we should definitely document SpeedCrunch behavior at the very least.

    Extra enhancements could be to let the user choose the behavior of the modulo function in such cases (through settings), and/or add a second modulo function which makes sure the sign of the result is always the same as the divisor.

  3. Mihai Ionescu reporter

    Choosing modulo behavior would be super! Especially if / when % operator would take modulo role

    It's way better to type just 1 character (%) instead of 6: m o d ( , )

  4. Lammen

    There is a connection between idiv and mod. It is desirable that dividend = quotient * divisor + remainder holds in all instances.

    So if you define idiv to be truncating, i.e. idiv(-0.5;1) = 0, mod is best designed as it is. I carefully chose these semantics roughly 10 yrs ago.

    In contrast, your mod(-1;360) = 359 suggestion requires idiv to behave like the floor function, i.e. idiv(-0.5;1) = -1. I consider this more disturbing than having mod(-1;360) = -1, which, by the way, can be memorized as "quotient and remainder have the same sign".

    The worst you can do, of course, is defining idiv one way, and mod the other, such leading to inconsistent definitions and compromising the idea, that idiv and mod are exact functions allowing you to recover the dividend from quotient, divisor and remainder unambiguously.

    Wolf

  5. Log in to comment