[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: div and mod.
bear <bear@xxxxxxxxx> writes:
> For what it's worth, here is the behavior that I as a programmer
> expect from Div and Mod.
> I expect mod always to return a number between zero inclusive and the
> modulus exclusive.
I agree. Haskell has two pairs of functions, where functions in each
pair are consistent with each other in the obvious way:
quot & rem - quot is rounded towards zero,
the sign of rem is the sign of the dividend
div & mod - div is rounded towards negative infinity,
the sign of mod is the sign of the divisor
(Plus quotRem and divMod which compute both together.)
| quot rem div mod
123 10 | 12 3 12 3
-123 10 | -12 -3 -13 7
123 -10 | -12 3 -13 -7
-123 -10 | 12 -3 12 -3
Both are primarily used with a positive divisor, in which case they
agree on non-negative dividends and provide two most common variants
on negative dividends.
The div & mod variant is more regular mathematically. When the divisor
is a power of 2, it corresponds to bit shifts and masks. Knuth warns
about programming languages which understand div & mod differently than
The quot & rem variant is consistent with Intel processors and C99,
absolute values of results are determined by absolute values of
The GMP library provides the above two families plus a yet another one,
rounding towards positive infinity.
I dislike using an entirely different variant when the divisor is
negative. If the variant with rounding to nearest is worth providing,
it should be a separate pair of functions. It's not clear how to
break ties: there are various subvariants possible.
__("< Marcin Kowalczyk