我正在读这个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
的非常慢的实现。
它将角度θ与(theta <= -pi || theta> = pi)映射到-pi ... pi的范围。
// if false theta is already >=-PI && <=PI
if ( fabs( theta ) <= PI ) {
// This is the range between -PI and PI
const float TWOPPI = 2.0f∗PI ;
// The next two steps are kind of an floating point modulo(theta,2PI)
float revolutions = floor (( theta + PI ) ∗ ( 1.0f /TWOPPI )) ;
theta −= revolutions ∗ TWOPPI ;
}
theta是rad