public static void Main() >>>> { >>>> var result = GetAverage(new int[] {357, 2, 359, 356, 4, 2, 355, 22}); //Result : 2 >>>> result = GetAverage(new int[] { 180, 182, 175, 178, 183, 185, 177, 172 }); //Result: 44 :-{ >>>> } >>>> >>>> public static double GetAverage(int[] values) >>>> { >>>> double c = 0; >>>> double s = 0; >>>> >>>> foreach (int i in values) >>>> { >>>> double r = DegreeToRadian(i); >>>> c += Math.Cos(r); >>>> s += Math.Sin(r); >>>> } >>>> >>>> double a = Math.Atan2(s, c); >>>> >>>> return RadianToDegree(a); >>>> } >>>> >>>> public static double DegreeToRadian(double angle) >>>> { >>>> return Math.PI * angle / 180.0; >>>> } >>>> >>>> public static double RadianToDegree(double angle) >>>> { >>>> return angle * (180.0 / Math.PI); >>>> }>>>> More testing......
>>> public static int GetAverage(IEnumerable<int> readings) >>> { >>> double s = 0.0, c = 0.0; >>> bool haveData = false; >>> >>> foreach (int value in readings) >>> { >>> double rads = DegreeToRadian(value); >>> >>> s += Math.Sin(rads); >>> c += Math.Cos(rads); >>> haveData = true; >>> } >>> >>> int result = 0; >>> if (haveData) >>> { >>> double rads; >>> >>> if (c == 0) >>> { >>> rads = s >= 0.00 ? Math.PI / 2.0 : -Math.PI / 2.0; >>> } >>> else >>> rads = Math.Atan2(s, c); >>> >>> result = (int)RadianToDegree(rads); >>> >>> } >>> return result; >>> } >>> public static double DegreeToRadian(double degrees) >>> { >>> return Math.PI * Modulo(degrees, 360.00) / 180.0; >>> } >>> >>> public static double RadianToDegree(double rads) >>> { >>> return Modulo(rads, Math.PI * 2) * (180.0 / Math.PI); >>> } >>> public static double Modulo(double dividend, double divisor) >>> { >>> return (dividend % divisor) >>> + (Math.Sign(dividend) * Math.Sign(divisor) >= 0 ? 0 : divisor); >>> } >>>I ended up with this (JScript):
function getAverageAngle(angleArray) { >> var c = 0; >> var s = 0; >> >> for (var i = 0; i < angleArray.length; i++) { >> var r = degreeToRadian(angleArray[i]); >> c += Math.cos(r); >> s += Math.sin(r); >> } >> var a = Math.atan2(s, c); >> var result = radianToDegree(a); >> if (result < 0) >> result = 360 + result; >> return result; >>} >> >>function degreeToRadian(angle) { >> return Math.PI * angle / 180; >>} >> >>function radianToDegree(angle) { >> return angle * (180 / Math.PI); >>}Raw and average seem to tally.