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.
|
I am unsure about how to simplify equations containing the modulo operator (%). Can this expresssion be simplified?
The values cannot be assumed to be integers. |
||||
| show 13 more comments |
|
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<aw$ then we have $$ \left(\left(X-aw\right)\%w\right).$$ |
|||||||||||
|
|
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:
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. |
|||||
|
X % w... – J. M. Jul 17 '11 at 0:54