# The Modulo function (%)

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

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

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.

http://en.wikipedia.org/wiki/Modulo_function

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

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

Not in this case, I want the values to wrap over.

Carsten