I'm reading this book and I came across this function wrapPi(). I know how to wrap an angle but what is exactly this code doing
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;
}
There is an error in this line:
It should be
This is the only condition under which you can't just return the existing value of
theta. The rest of theifstatement works out how many times you need to add or subtract 2*PI in order to find the angle equivalent tothetain the correct range.Personally I prefer to write separate code blocks for
if (theta <= -PI)andif (theta > PI), but that's possibly a prejudice due to encountering a very slow implementation offabsin the past.