Sunday, 9 November 2014

Calculate Mean, Median, Mode Averages, StandardDeviation in C#

protected void Page_Load(object sender, EventArgs e)
{
List<double> doubleList = new List<double>();
doubleList.Add(10.00);
doubleList.Add(555.00);
double std = getStandardDeviation(doubleList);
double median = getMedian(doubleList);
double mean = getMean(doubleList);
IEnumerable<double> modes = getModes(doubleList);
}

private double getMedian(List<double> list)
{
List<double> orderedList = list
.OrderBy(numbers => numbers)
.ToList();

int listSize = orderedList.Count;
double result;

if (listSize % 2 == 0) // even
{
int midIndex = listSize / 2;
result = ((orderedList.ElementAt(midIndex - 1) +
  orderedList.ElementAt(midIndex)) / 2);
}
else // odd
{
double element = (double)listSize / 2;
element = Math.Round(element, MidpointRounding.AwayFromZero);

result = orderedList.ElementAt((int)(element - 1));
}

return result;
}
private double getMean(List<double> list)
{
return list.Average();
}
private IEnumerable<double> getModes(List<double> list)
{
var modesList = list
.GroupBy(values => values)
.Select(valueCluster =>
new
{
Value = valueCluster.Key,
Occurrence = valueCluster.Count(),
})
.ToList();

int maxOccurrence = modesList
.Max(g => g.Occurrence);

return modesList
.Where(x => x.Occurrence == maxOccurrence && maxOccurrence > 1)
.Select(x => x.Value);
}
private double getStandardDeviation(List<double> doubleList)
{
double M = 0.0;
double S = 0.0;
int k = 1;
foreach (double value in doubleList)
{
double tmpM = M;
M += (value - tmpM) / k;
S += (value - tmpM) * (value - M);
k++;
}
return Math.Sqrt(S / (k - 2));
}

No comments:

Post a Comment

Get all non-clustered indexes

DECLARE cIX CURSOR FOR     SELECT OBJECT_NAME(SI.Object_ID), SI.Object_ID, SI.Name, SI.Index_ID         FROM Sys.Indexes SI             ...