Advertisement

good way to clamp angle

Started by April 04, 2001 11:06 AM
3 comments, last by Thrump 23 years, 10 months ago
If you always want your angle between -PI and +PI (or any other full circle of rotation), what is the best way to do it? For example, and angle of 2*PI is too big and is equivalent to 0, so replace it with 0. Right now I''m using a loop that subtracts or adds 2*PI until the angle is valid. If you had to do this many many times, it is kind of inefficient. Any way with the modulus operation if you''re using floats? Thx!
You can use the repeated substraction without huge huge waste of time like this:

        #define PI 3.1414void trim (double &x){	while (x > PI * 999.0)		x -= PI * 1000.0;	while (x > PI * 99.0)		x -= PI * 100.0;	while (x > PI * 9.0)		x -= PI * 10.0;	while(x > PI)		x -= PI * 2.0;//...... same for negative}  This is the much better divide method :      void trim(double &x){	if (x > PI)		x -= floor((x - PI) / (PI * 2.0)) * PI * 2.0;	if (x < -PI)		x -= ceil((x + PI) / (PI * 2.0)) * PI * 2.0;}    




Edited by - Diodor on April 4, 2001 1:06:30 PM

Sorry bout the buggy code. Hope this one does it.

Edited by - Diodor on April 5, 2001 6:09:41 PM
Advertisement
angle = fmod(angle, TWO_TIMES_PI);
Thx, the floor/ceiling way works, with some minor adjustments. (your code moves in PI increments, and in radians angle != angle + PI) Didn''t try the fmod thing but it looks like it would work too.
I think that mathematically the floor/ceil method and the fmod method to exactly the same thing. However, depending on your compiler vendor''s implmentation of fmod, it might be a bit faster. (Not 100% sure though, I haven''t tested it or anything).

This topic is closed to new replies.

Advertisement