public Statistics(IEnumerable <double> values) { originalValues = values.Where(d => !double.IsNaN(d)).ToList(); sortedValues = originalValues.ToList(); N = sortedValues.Count; if (N == 0) { throw new InvalidOperationException("Sequence of values contains no elements, Statistics can't be calculated"); } sortedValues.Sort(); if (N == 1) { Q1 = Median = Q3 = sortedValues[0]; } else { double GetMedian(IList <double> x) => x.Count % 2 == 0 ? (x[x.Count / 2 - 1] + x[x.Count / 2]) / 2 : x[x.Count / 2]; Median = GetMedian(sortedValues); Q1 = GetMedian(sortedValues.Take(N / 2).ToList()); Q3 = GetMedian(sortedValues.Skip((N + 1) / 2).ToList()); } Min = sortedValues.First(); Mean = sortedValues.Average(); Max = sortedValues.Last(); InterquartileRange = Q3 - Q1; LowerFence = Q1 - 1.5 * InterquartileRange; UpperFence = Q3 + 1.5 * InterquartileRange; AllOutliers = sortedValues.Where(IsOutlier).ToArray(); LowerOutliers = sortedValues.Where(IsLowerOutlier).ToArray(); UpperOutliers = sortedValues.Where(IsUpperOutlier).ToArray(); Variance = N == 1 ? 0 : sortedValues.Sum(d => Math.Pow(d - Mean, 2)) / (N - 1); StandardDeviation = Math.Sqrt(Variance); StandardError = StandardDeviation / Math.Sqrt(N); Skewness = CalcCentralMoment(3) / StandardDeviation.Pow(3); Kurtosis = CalcCentralMoment(4) / StandardDeviation.Pow(4); ConfidenceInterval = new ConfidenceInterval(Mean, StandardError, N); Percentiles = new PercentileValues(sortedValues); }
public Statistics(IEnumerable <double> values) { list = values.ToList(); N = list.Count; if (N == 0) { throw new InvalidOperationException("Sequence of values contains no elements, Statistics can't be calculated"); } list.Sort(); if (N == 1) { Q1 = Median = Q3 = list[0]; } else { Func <IList <double>, double> getMedian = x => x.Count % 2 == 0 ? (x[x.Count / 2 - 1] + x[x.Count / 2]) / 2 : x[x.Count / 2]; Median = getMedian(list); Q1 = getMedian(list.Take(N / 2).ToList()); Q3 = getMedian(list.Skip((N + 1) / 2).ToList()); } Min = list.First(); Mean = list.Average(); Max = list.Last(); InterquartileRange = Q3 - Q1; LowerFence = Q1 - 1.5 * InterquartileRange; UpperFence = Q3 + 1.5 * InterquartileRange; Outliers = list.Where(IsOutlier).ToArray(); Variance = N == 1 ? 0 : list.Sum(d => Math.Pow(d - Mean, 2)) / (N - 1); StandardDeviation = Math.Sqrt(Variance); StandardError = StandardDeviation / Math.Sqrt(N); Skewness = CalcCentralMoment(3) / StandardDeviation.Pow(3); Kurtosis = CalcCentralMoment(4) / StandardDeviation.Pow(4); ConfidenceInterval = new ConfidenceInterval(Mean, StandardError); Percentiles = new PercentileValues(list); }