• Advertisement
Sign in to follow this  

keep value within the range of radians

This topic is 3389 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

My current code:
if (x < -PI)
    x += TWOPI;
else
if (x >  PI)
    x -= TWOPI;
The problem: x could be 400.0 or more, under those circumstances this wrapping method fails. I need to keep x in the radian range, always. Any ideas? Thanks

Share this post


Link to post
Share on other sites
Advertisement
Really? that's just pseudo code in fact. I'm coding in C++. I just drew a blank and I can't think of any good way of doing this...

Right now I'd have to apply the aforementioned statement on each update instead of every now and then (when I actually do require X to be in that range). It's a small piece of code and it won't kill any performance at all I was just wondering though if there could be a better way of doing it.

Share this post


Link to post
Share on other sites
How would you go about using modulo (fmod as suggested) when the variable starts on -PI and ends as PI ? (full range) -- take a look at my pseudo code to see what I mean.

Share this post


Link to post
Share on other sites
Quote:
Original post by gusso
Really?
Absolutely, imagine if you'd picked a language that has a wrapping function already [smile]

Quote:
I'm coding in C++. I just drew a blank and I can't think of any good way of doing this...
This is a common and fairly unsophisticated solution:

template <typename T>
T wrap(T value, T lower, T upper)
{
T r = upper - lower;
while (upper < value) value -= r;
while (value < lower) value += r;
return value;
}

// ...
x = wrap(x, -PI, PI);

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement