keep value within the range of radians

Started by
5 comments, last by dmatter 15 years, 3 months ago
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
Advertisement
The best answer may depend on the language...
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.
Modular arithmetic is an alternative.
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.

  x = fmod(x, TWO_PI);  if (x > PI) x -= TWO_PI
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);

This topic is closed to new replies.

Advertisement