3
$\begingroup$

I am unsure about how to simplify equations containing the modulo operator (%). Can this expresssion be simplified?

(((X - aw) % w) - w) % w 

The values cannot be assumed to be integers.

  • 0
    I'm perfectly aware @soa$n$dos; I suppose I have been spoiled by working in environments where the "binariness" of the arithmetic is mostly under the hood and .9/.1 gives 9.00000... :)2011-07-17

2 Answers 2

2

In C#, the modulo operator gives a negative value if one of the arguements is negative, and positive otherwise. So 5%2==1, and -4%3==-1. To get the "standard" modulo answer, you just have to test if its negative, and if so, add the modulus (if you want a branchless if here, just add the modulus and then take the result modulo the modulus).

Given that, you expression reduces to what @eric said:

If X≥aw then we have ((X−aw)%w)−w, and if X < aw then we have ((X−aw)%w).

EDIT: Warning, working with floats/doubles introduces error into your calculations. You may find it a better idea to use decimal as it preserves the decimal digits that you are working with.

  • 0
    Apologies, there was a weird (to me) formmating issue (the '<' hid the rest of the line.2011-07-17
1

Stranger things happen if the numbers are negative. Suppose they are positive. If $X\geq aw$ then we have $ \left(\left(X-aw\right)\%w\right)-w,$ and if $X then we have $ \left(\left(X-aw\right)\%w\right).$

  • 0
    @Eric: I agree that it sounds wrong. This was discussed in sci.math ages ago, and IIRC the explanation went something like this. Two integer operations were to be defined: $a\%b$ and $a DIV b$. IOW $a,b$ are integers, $b\neq0$ and so should the answers. A starting point was that $a DIV b:=[a/b]$ for positive integers. Another starting point was that the equation $ a= (a DIV b) b + (a\%b)$ should always be true. Sounds reasonable, but then adding yet another "reasonable" premise $(-a) DIV b = -(a DIV b)$ to the mix lead to the conclusion that $a\%b$ had to be occasionally negative.2011-07-17