For modulo, I find the following simplest. No matter what the implementation declaration agreement means, we simply force the result to the sign we need:
r = n % a; if (r < 0) r += a;
Obviously, for positive a. For negative, you need:
r = n % a; if (r > 0) r += a;
Which (perhaps a little vaguely) combines to give the following (in C ++. In C, doing the same with int and then tiring to write a duplicate for a long time):
template<typename T> T sign(T t) { return t > T(0) ? T(1) : T(-1); } template<typename T> T py_mod(T n, T a) { T r = n % a; if (r * sign(a) < T(0)) r += a; return r; }
We can use the two-digit sign function cheapskate because we already know a! = 0, or% will be undefined.
Applying the same principle to division (look at the output, not the input):
q = n / a;
Multiplications may possibly be more expensive than necessary, but if necessary they can be optimized with a micro-level structure based on each architecture. For example, if you have a division operation that gives you a ratio and a remainder, then you are sorted for division.
[Edit: there may be some cross cases where this does not happen, for example, if the quotient or the rest is INT_MAX or INT_MIN. But emulating python math for large values โโis another question :-)]
[Other editing: not a standard python implementation written in C? You can trawl the source for what they do]
Steve Jessop May 6 '09 at 12:41 2009-05-06 12:41
source share