Q: Feature Wish: "%" Extension

Jive Dadson jdadson at ix.netcom.com
Mon Nov 5 05:51:31 CET 2001

Tim Peters wrote:
> [Jive Dadson]
> > I work in robotics.  Our robots have several rotary axes, each of which
> > can turn considerably more than 360 degrees.  The positions 5 degrees
> > and 365 degress are not equivalent, because the arms can contain wires
> > and tubes that can only be twisted so many times.  I am continually
> > using the following function, often to "mod out" multiples of 360
> > degrees.
> >
> > // "Floating point modulus" function
> > inline double fpMod(double x, double modulus) {
> >     return  x-floor(x/modulus)*modulus;
> > }
> Why do you use that instead of the platform fmod() function?  Is it
> important that the result be non-negative in this application?

It is (semi) important that it always return a number in SOME canonical
span of 360. It would be okay if it always returned a number in the
range -180 to 180, for example.  But if it returned a number in the
range -360 to 360, I would have to put extra tests in the code.

Now a confession.  I didn't know about fmod().  If I had, I might have
coded fpMod as follows, sticking the unavoidable test into the function

double fpMod(double x, double modulus) {
    double retval = fmod(x,modulus);
    if(retval < 0) {
        retval += modulus;
    return retval;

More information about the Python-list mailing list