Difference Bearing Calculator in PHP

A long standing application checks the actual weather reports for various UK airfileds and then compares to a forecast. One of the variables is the wind direction.

The application compares a compass bearing for the actual and forecasted wind direction and then states the difference in degrees. All sounds easy. Alas the first release of PHP code for this seemed to be incorrect for the fourth quarter (i.e. Q4 is between 270 and 360 degrees).

Here’s the code that has now been proven to work.

Function FindBearing( $forecast, $actual )
{

    if ($actual == "VRB") { 
        // the forecast has variable so we return zero 
        // as it could be anything given the winds are light, 
        // that's not something we can handle
        return 0;
    }
    
    if  ($forecast <= 180 ) { // in Q1 or Q2
        if ( $actual <= 180 ) { // in Q1 or Q2
            return abs($actual - $forecast);
        } 
        // forecast in Q3 or Q4
        return 180-abs((360-$actual)-abs(180-$forecast));
        
    } else { // forecast in Q3 or Q4
        if ( $actual > 180 ) { // forecast in Q3 and Q4 as well so easy
            return abs($actual - $forecast);
        }
        
        // forecast in Q3 or Q4 and forecast in Q1 and Q2
        $result = abs($actual - $forecast);
        
        if ($result <= 180){
            return $result;
        }
        return 180 - abs(180-$result);
    }

    // else return a bearing that isn't possible     
    return "-1";
}

The function can be tested by using this simple PHP script:


for ($i = 0; $i <= 360; $i=$i + 1) {
        for ($j = 0; $j <= 360; $j=$j + 1) {
            $diff = FindBearing( $i, $j );
            
            echo "
forecast=$i, actual=$j, diff=$diff"; if (($diff < 0) || ($diff>180)){ echo "ERROR"; } } }