a % b == b when a is a very small negative number

Lee Harr missive at frontiernet.net
Sun Nov 24 11:15:08 EST 2002


I have some code which is storing the direction an object
is moving, and I want to keep that value: 0 <= direction < 2*PI

So I do something like this:

class Directed:
    def setDirection(self, direction):
        self.direction = direction % (2*PI)  # PI = math.pi

This works fine until direction is some very very small negative number,
like -0.1e-16.

With that input, self.direction == 2*PI.


What I do right now to work around this is take the modulus twice:

    def setDirection(self, direction):
        self.direction = direction % (2*PI) % (2*PI)  # weird, but works

Though thinking about it now, it might be better to simply
check for a very small number:

    def setDirection(self, direction):
        if direction> 0 and direction < 0.00001:
            self.direction = 0
        else:
            self.direction = direction % (2*PI)


Is this not a proper use of the % operator?
Should not a % b always be less than b?




More information about the Python-list mailing list