I was looking for a way to average degrees for a project I'm working on and didn't want to use vector addition. So, I've implemented a median function in the RunningMedian library for compass readings to compensate for hassles of degree wraps at 359-0. This is based a previous version, not the current version of the library. Feel free to incorporate it into your library for others to use, if you wish.

`/* function by WethaGuy to allow determination of median of a set of degrees, accounting for the 359-0 wrap */`

int RunningMedian::getMedianDegrees()

{

if (_cnt > 0){

int index = 0;

sort();

/*check for valid compass value 0-359*/

if (_as[_cnt-1] > 359 || _as[0] < 0){return NAN;}

/*check 359-0 wrap*/

if (_as[_cnt-1]-_as[0] > 180){

/*find the index value of wrap*/

while(_as[index+1]-_as[index] < 180){

index++;

}

/* index value is less than the center of the list, the median is the sum of the index and the center of the list plus one (to account for odd number total list size) */

if (index < (_cnt/2)){

return _as[(_cnt/2) + index +1];

/*index value is not less than center of list, the median is the difference between center of the list and the index */

}else{

return _as[index -(_cnt/2)];

}

}

/* no 360-0 wrapping needed */

return _as[_cnt/2];

}

return NAN;

}

edited code to correct error, 8/20/13.