我正在读这个 book我遇到了这个函数 wrapPi()
。我知道如何包角,但这段代码到底在做什么
float wrapPi ( float theta ) {
// Check if already in range. This is not strictly necessary,
// but it will be a very common sit u a t i o n . We don ’ t want to
// incur a speed hit and perhaps floating precision loss if
// it’s not necessary
if ( fabs( theta ) <= PI ) {
// One revolution is 2PI .
const float TWOPPI = 2.0f∗PI ;
// Out of range. Determine how many ”revolutions”
// we need to add .
float revolutions = floor (( theta + PI ) ∗ ( 1.0f /TWOPPI )) ;
// Subtract it off
theta −= revolutions ∗ TWOPPI ;
}
return theta;
}
最佳答案
这一行有错误:
if ( fabs( theta ) <= PI ) {
应该是
if ( fabs( theta ) > PI ) {
这是唯一不能只返回 theta
的现有值的情况.
其余if
语句计算出您需要添加或添加多少次
减去 2*PI 以找到等于 theta
的角度在正确的范围内。
我个人更喜欢为 if (theta <= -PI)
编写单独的代码块
和 if (theta > PI)
,但这可能是由于遇到的偏见
fabs
的执行非常缓慢过去。
关于c++ - 这是环绕角度的正确代码吗 (-180,180],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26948968/