Modular arithmetic
Richard Haseltine
Posts: 100,926
I would expect any operation mod n to return a value in [ 0 , n - 1 ]. Using the % operator in Daz Script that works for addition but not for subtraction:
for ( var i = 0 ; i < 4 ; i++ ) { print ( ( i + 1 ) % 4 ); print ( ( i - 1 ) % 4 );}
returns:
1
-1
2
0
3
1
0
2
instead of the expected (by me):
1
3
2
0
3
1
0
2
Which of us is wrong, Daz Script or me? And if it's the latter, is there a neater way to get my expected behaviour than testing for 0 in subtraction operations and giving it a special result of n - 1 instead of -1?
Comments
I think the way you stacked the prints DAZ is correct.
0+1 mod 4 = 1
0-1 mod 4 = -1
1+1 mod 4 = 2
1- 1 mod 4 = 0
2+1 mod 4 = 3
2-1 mod 4 -= 1
3+1 mod 4 = 0
3-1 mod 4 = 2
OK, thanks.
for ( var i = 4 ; i > 0 ; i-- ) {
print ( ( i + 1 ) % 4 );
print ( ( i - 1 ) % 4 );
}
Would give you your expected: 1, 3, 0, 2, 3, 1, 2, 0
Speaking as a mathematician, no. It's seriously messing up on handling negative values.
Thanks, that is reassuring - though if it is a bug it's presumably a Qt bug, not soemthign that Daz can fix.
not useful though, unfortunately, as I am dealing in the real case with array indices which start at 0 and run to n-1.
Aha, Rob points out that the operator is a remainder operator, not a true modulo operator https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Remainder_() . So the issue is not "bad modular maths" but "thinking it was modular maths when it wasn't".
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Remainder_()
((x % y) + y) % y
should give you a true modulus, if I'm understanding the function properly.Yes, that looks logical.