CroCo
CroCo

Reputation: 5741

Is this correct code for wrapping an angle (-180,180]

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

Answers (2)

David K
David K

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

Oncaphillis
Oncaphillis

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

Related Questions