开发者

C++, fastest method of getting angle into a specified range?

what's the fastest way of getting a variable into a given range? For example, make sure that an angle "double alpha" is always within (0.0, 2*Pi).

I found two 开发者_运维问答solutions myself, one of them is much slower and the other looks way to complicated for such an easy task. There must be a better way, or not?

//short, but very slow (so it's a no-go);
return asin(sin(alpha));

//much faster, but seems ugly (two while loops to change a variable? come on!)
while (alpha < 0.0)
{
    alpha += 2.0 * M_PI;
}
while (alpha >= 2.0 * M_PI)
{
    alpha -= 2.0 * M_PI;
}
return alpha;


Instead of implementing this by hand, I suggest you use the fmod() family of functions: http://linux.die.net/man/3/fmodf which does exactly this. You'll still need to take care of negative results yourself, though:

alpha = fmod(alpha, 2.0 * M_PI);
if (alpha < 0.0)
    alpha += 2.0 * M_PI;
return alpha;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜