|
01 Mar 2015 by Andy
Mean AngleDescriptionArithmetic 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. InputAn IEnumerable<double> expecting angle values in radians OutputThe mean angle in radians Contract
IMathUtilities
double MeanAngle(IEnumerable<double> angleValues);
Test Cases
MeanAngleof0and360_ShouldBeZero
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);
}
MeanAngleOfMoreThanTwoAngles_ShouldReturnCorrectValue
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);
}
MeanAngleofSingleAngleShouldReturnSame
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
|
|
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
|
||||
download solution | ||||
Try this Solution | ||||
Comments
|
|
31 Mar 2015 by bobloki
Turned it into a one liner linq statement.
public class Solution : IMathUtilities
{
public double MeanAngle(IEnumerable<double> angleValues)
{
return Math.Atan2(angleValues.Sum(i => Math.Sin(i)) / angleValues.Count(),
angleValues.Sum(i => Math.Cos(i)) / angleValues.Count());
}
}
|
|||
|
||||
Test Case Run Summary
MeanAngleof0and360_ShouldBeZero
MeanAngleOfMoreThanTwoAngles_ShouldReturnCorrectValue
MeanAngleofSingleAngleShouldReturnSame
|
||||
download solution | ||||
Try this Solution | ||||
Comments
|