in reply to Re: Modulus Inconsistencies (Or Calling all Mathematicians)
in thread Modulus Inconsistencies (Or Calling all Mathematicians)

As the co-worker who ran smack into this problem, I think the question that I would really like to find out is:
So, which is the more common result?
I can see both of these being solutions to that equation:
x = q * d + r -7 = 4 * d + r So for d = -1, r = -3 And for d = -2, r = 1
In the code I'm writing I have use for both of these results, so neither is more or less correct. I just thought that there was a commonly accepted algorithm (as there is for positive modulo) for this.
I think it really comes down to how the rounding operation works.

Replies are listed 'Best First'.
Re: Re: Re: Modulus Inconsistencies (Or Calling all Mathematicians)
by no_slogan (Deacon) on Mar 26, 2003 at 19:30 UTC
    So, which is the more common result?

    Unfortunately, there's no good answer. Hardware vendors choose different ways of implementing division, because division is complicated. Language specifications usually let the compiler go with whatever the underlying hardware does, for speed. Division with round-towards-zero (which can produce a negative remainder) is common in modern systems, but nobody is making you any guarantees.

    If getting consistent results across different platforms is important to you, you can always calculate the remainder by hand.

    $q = int($x / $d); $r = $x - $d * $q;

    Of course, that costs you an extra multiply and subtract.

    I think it really comes down to how the rounding operation works.

    Precisely.

Re3: Modulus Inconsistencies (Or Calling all Mathematicians)
by dragonchild (Archbishop) on Mar 26, 2003 at 19:24 UTC
    The question is "Which is the more commonly accepted result?". The answer to that is the positive number. Perl is right, C is wrong (but quicker, if you're into that sort of thing).

    ------
    We are the carpenters and bricklayers of the Information Age.

    Don't go borrowing trouble. For programmers, this means Worry only about what you need to implement.

    Please remember that I'm crufty and crochety. All opinions are purely mine and all code is untested, unless otherwise specified.