[Tutor] x%2
Steven D'Aprano
steve at pearwood.info
Tue Jan 10 22:58:35 CET 2012
bob gailer wrote:
> On 1/10/2012 1:47 PM, Noah Hall wrote:
>> a % b is the remainder operator. It returns what's "left" after
>> dividing a by b.
> Not to beat a dead horse- but % is the modulo operator.
That depends on how you define "remainder" and "modulo". There is no
definition agreed on by all people, and so we get into terminology disputes.
To a mathematician, "modulo operator" is meaningless. Modulo is a modifier to
a statement, not an operator, and is written "mod" as in:
1 = 5*3 mod 7
> It returns the residue class of the 2 operands. When a is positive this
> is the same as remainder, but not so for negative a.
"Remainder" is ambiguous for negative values. -7/5 could be given as -1 with
-2 remainder, or as -2 with 3 remainder. One might define a remainder
operation as returning a result:
- which is always positive
- with the sign of the divisor
- with the sign of the dividend
- which is closest to zero
- which is furthest away from zero
The last two require further variations, depending on how you resolve ties.
One might also define i%0 to be i, or as undefined. So by my count, there are
at least 18 consistent ways to define a remainder/modulo operator.
A very few languages define two operators, or functions, e.g. Ada defines a
rem operator which returns the remainder with the sign of the dividend and a
mod operator which returns the remainder with the sign of the operator.
--
Steven
More information about the Tutor
mailing list