01 Mar 2015 by Andy

# Mean Angle

#### Description

Arithmetic mean may not always be suited for circular quantities like angles, day times, fractional quantities. e.g Mean angle of 0 degrees & 360 degrees arithmetically is 180. However, 0 degrees & 360 degrees are the same value and the mean should be zero.

#### Input

An IEnumerable<double> expecting angle values in radians

#### Output

Contract
IMathUtilities
double MeanAngle(IEnumerable<double> angleValues);
Test Cases
 vote buttons 0
Created By Super Human
public void MeanAngleof0and360_ShouldBeZero(IMathUtilities m) { double tolerance = 0.0000000001; Assert.AreEqual(0, m.MeanAngle(new double[] { 0, 2*Math.PI }), tolerance); }
 vote buttons 0
Created By Super Human
public void MeanAngleOfMoreThanTwoAngles_ShouldReturnCorrectValue(IMathUtilities m) { double tolerance = 0.0000000001; Assert.AreEqual(-Math.PI/2, m.MeanAngle(new double[] { Math.PI / 2, Math.PI, (3d/2d) * Math.PI, 2 * Math.PI}), tolerance); }
 vote buttons 0
Created By K Bonneau
public void MeanAngleofSingleAngleShouldReturnSame(IMathUtilities m) { double tolerance = 0.0000000001; Assert.AreEqual(Math.PI, m.MeanAngle(new double[] { Math.PI }), tolerance); }
You must be logged in to add test cases

## 2 Solutions

01 Mar 2015 by Andy
For circular mean, we need to find both the x & y components for each angle (assuming they are part of the unit circle). i.e. x component would be the Cosine of the angle, and y component is the Sine of the angle. Find the mean separately for both the components, and then do the reverse, i.e find the angle from these mean components using arc tangent function.
public class Solution : IMathUtilities { public double MeanAngle(IEnumerable<double> angleValues) { double xValue = 0, yValue = 0; int numValues = 0; foreach(var angle in angleValues) { xValue += Math.Cos(angle); yValue += Math.Sin(angle); numValues++; } return Math.Atan2 (yValue / numValues, xValue / numValues); } }
Test Case Run Summary
MeanAngleof0and360_ShouldBeZero
MeanAngleOfMoreThanTwoAngles_ShouldReturnCorrectValue
MeanAngleofSingleAngleShouldReturnSame