Reputation: 5741
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;
}
Upvotes: 0
Views: 1786
Reputation: 3132
There is an error in this line:
if ( fabs( theta ) <= PI ) {
It should be
if ( fabs( theta ) > PI ) {
This is the only condition under which you can't just return the existing value of theta
.
The rest of the if
statement works out how many times you need to add or
subtract 2*PI in order to find the angle equivalent to theta
in the correct range.
Personally I prefer to write separate code blocks for if (theta <= -PI)
and if (theta > PI)
, but that's possibly a prejudice due to encountering
a very slow implementation of fabs
in the past.
Upvotes: 2
Reputation: 1908
It maps angle theta with (theta <= -pi || theta >= pi) into the range of -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 is in rad
Upvotes: 0