C: is there anyway i can get the modulo operator to work on non integer values?

Viewed 439

I need to reset the value of a variable called theta back to 0 everytime its value reaches or exceeds 2 PI. I was thinking something along the lines of:

int n = 10;
float inc = 2*PI/n;
for(int i=0;i<10;i++)
    theta = (theta + inc) % 2*PI;

Of course it wont work because % doesn't work on floating points in C. Is there another equivalent or better way to achieve what I'm trying to do here? All replies are welcome. Thanks

2 Answers

Since division is really just repeated subtraction, you can get the remainder by checking if the value is at least 2*PI, and if so subtract that value.

int n = 10;
float inc = 2*PI/n;
for(int i=0;i<10;i++) {
    theta += inc;
    if (theta >= 2*PI)  theta -= 2*PI;
}

Note that because the amount of the increment is less than the 2*PI limit we can do the "over" check just once. This is likely cheaper than the operations that would be involved if fmod was called. If it was more you would at least need while instead, or just use fmod.

Use the standard fmod function. See https://en.cppreference.com/w/c/numeric/math/fmod or 7.2.10 in the C17 standard.

The fmod functions return the value x − n y , 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.

So theta = fmod(theta, 2*PI) should be what you want, if I understand your question correctly.

If it really must be done on float instead of double, you can use fmodf instead.

Related