Search code examples
c++modulo

How to get the positive modulo between floating-point numbers


I have a real number x and I want to get the number (x mod 2*PI) = y, where y is between 0 and 2*PI.

I could do it with a loop and if x is negative I just keep adding 2*pi until my number is in range of [0,2*pi] or if x is greater the 2*pi I could just keep subtracting. However, I hope there is a more elegant way to do this.

I tried this:

fmod(-0.3434073,2*M_PI);

but this remains -0.3434073. Why and how can I get it working as I want it to?


Solution

  • Edit: Credits to Notinlist for answering faster.

    In the C99 standard, section 7.12.10.1 has this to say:

    The fmod functions return the value x − ny, for some integer n such that, if y is nonzero, the result has the same sign as x and magnitude less than the magnitude of y. If y is zero, whether a domain error occurs or the fmod functions return zero is implementation- defined.

    Going by this, you need to add y if you want the proper sign.

    All in all:

    double fmod_positive(double x, double y){
        double tmp = fmod(x, y);
        return x < 0 ? tmp + y : tmp;
    }