modulo

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
 
D

Doug Semler

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
 
J

Jon Skeet [C# 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?

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top