Skip to content

Commit

Permalink
Added the Median() method (#54)
Browse files Browse the repository at this point in the history
  • Loading branch information
lpeyr committed Jan 7, 2023
1 parent 5617ee1 commit edc11c3
Showing 1 changed file with 29 additions and 0 deletions.
29 changes: 29 additions & 0 deletions PeyrSharp.Core/Maths/Stats.cs
Original file line number Diff line number Diff line change
Expand Up @@ -51,5 +51,34 @@ public static double Mean(List<double> values)

return mean;
}

public static double Median(List<double> values)
{
// Check for empty input
if (values.Count == 0)
{
throw new ArgumentException("Cannot calculate median of empty dataset", "values");
}

// Sort values
values.Sort();

// Calculate median
double median;
int n = values.Count;
if (n % 2 == 1)
{
// Odd number of elements
median = values[n / 2];
}
else
{
// Even number of elements
median = (values[n / 2 - 1] + values[n / 2]) / 2;
}

return median;
}

}
}

0 comments on commit edc11c3

Please sign in to comment.