modulo

  • Thread starter Thread starter Michel Walsh
  • Start date Start date
M

Michel Walsh

Mathematically, r = a modulo b (b being the divisor) is defined such
that if b <> 0, and if r <>0, its sign should be the sign of b.

C# does not follow this definition.

int indx = -1;
indx %= 100;


will let indx == -1, not == 99 as it should (mathematical definition).



Is that "by specification"? and if so, is there an alternate predefined
'modulo' operator which behaves like the mathematical definition?


Thanks for your time,
Vanderghast, Access MVP
 
Mathematically, r = a modulo b (b being the divisor) is defined such
that if b <> 0, and if r <>0, its sign should be the sign of b.

C# does not follow this definition.

int indx = -1;
indx %= 100;

will let indx == -1, not == 99 as it should (mathematical definition).

Is that "by specification"? and if so, is there an alternate predefined
'modulo' operator which behaves like the mathematical definition?

C# takes the sign of the dividend, not divisor. (There is another
thread recently discussing this very thing).
a = dividend;
n = divisor;
r = a - n * Floor(a / n) when result of a/n is positive
r = a - n * Cieling(a / n) when result of a/n is negative.

As a result of this, r takes the sign of the dividend...

Besides, longhand, the remainder comes up -1 <g>
-1 % 100 = -1:

___0_____
100 | -1
0
______
-1 <--- remainder

1 % -100 = 1:

___0_____
-100 | 1
0
______
1 <--- remainder
 
Mathematically, r = a modulo b (b being the divisor) is defined such
that if b <> 0, and if r <>0, its sign should be the sign of b.

C# does not follow this definition.

int indx = -1;
indx %= 100;

will let indx == -1, not == 99 as it should (mathematical definition).

Is that "by specification"? and if so, is there an alternate predefined
'modulo' operator which behaves like the mathematical definition?

Yes, it's by specification. It's also what many (but not all) other
languages do.

I believe it's partly the choice due to division rounding towards 0.
So if you consider:

div = x / y;
rem = x % y;

x = div*y + rem

If x is -1 and y is 100, then div will be 0, and rem is -1.
The alternative would be for div to be -1 with rem as 99, *or* make
the above relation not hold.

Jon
 
Back
Top