calli
March 10, 2009, 9:18am
1
Hi,
I just discovered that the modulo (%) function in the arduino ide is a mathematical, not a symmetrical like in most(?) other programming languages.
Is there a reason using this implementation? Is there somewhere a hidden modulo using the symetrical function?
Thanks,
Carsten
calli
March 10, 2009, 9:42am
2
Strange...
Python:
z1 = -2
z2 = 15
print z1 - ((z1 / z2) * z2)
13
But in C (Arduino IDE) its still giving negative numbers...
int smod(int z1, int z2) {
return(z1 - ((z1 / z2) * z2));
}
Any suggestions?
Carsten
But in C (Arduino IDE) its still giving negative numbers...
Exactly what is the result in C? I would expect it to be -2, but I haven't tested this. -2 - (0 * 15) = -2
I'm not familiar with Python, but from the result it looks like the equation is not equal to the C-example. It looks like -2 - (-1 * 15) = 13.
So in C the division -2/15 = 0 with a remainder of -2. I'm not familiar at all with Python so I can't say why -1/15 = -1
system
March 10, 2009, 10:08am
4
return(z1 - ((z1 / z2) * z2));
This is essentially the same as 0, but because of the truncation it might result in something other than 0.
I just discovered that the modulo (%) function in the arduino ide is a mathematical, not a symmetrical like in most(?) other programming languages.
I don't know what you mean by "mathematical" and "symmetrical", but modulo in C (and the "Arduino language" is plain C/C++ with some supporting libraries) is the remainder of an integer division.
calli
March 10, 2009, 12:16pm
6
In computing, the modulo operation returns the remainder or signed remainder of a division, after one number is divided by another (called the modulus of the operation).
Given two positive numbers a and n, a modulo n (often abbreviated as a mod n) is the remainder of the Euclidean division of a by n, where a is the dividend and n is the divisor.
For example, the expression "5 mod 2" would evaluate to 1, because 5 divided by 2 has a quotient of 2 and a remainder of 1, while "9 mod 3" would evalu...
I think what I was talking about as symmetrical is the "Euclidian Division".
I use the modulo in Python regularly for clipping values to a range.
For now I used this:
int smod(int z1, int z2) {
int ze;
ze=z1 % z2;
if (ze>=0) {
return(ze);
}
else{
return(z2+ze);
}
}
For my special case (modulo 2 and 16, all modulo power of 2) I can also use
x & 1 and x & 15
Carsten
mem
March 10, 2009, 12:32pm
7
I use the modulo for clipping values to a range.
would the constrain function do what you want?
http://www.arduino.cc/en/Reference/Constrain
calli
March 10, 2009, 1:06pm
8
Not in this case, I want the values to wrap over.
See: http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1236549392/6#6
Carsten