Free cookie consent management tool by TermsFeed Policy Generator

Changeset 14011 for trunk/sources


Ignore:
Timestamp:
07/06/16 19:46:28 (8 years ago)
Author:
mkommend
Message:

#2628: Added methods for calculating the population stddev and variance of IEnumerable<double>.

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/sources/HeuristicLab.Common/3.3/EnumerableStatisticExtensions.cs

    r13059 r14011  
    164164
    165165    /// <summary>
    166     /// Calculates the standard deviation of values.
     166    /// Calculates the sample standard deviation of values.
    167167    /// </summary>
    168168    /// <param name="values"></param>
     
    173173
    174174    /// <summary>
    175     /// Calculates the variance of values. (sum (x - x_mean)² / n)
     175    /// Calculates the population standard deviation of values.
     176    /// </summary>
     177    /// <param name="values"></param>
     178    /// <returns></returns>
     179    public static double StandardDeviationPop(this IEnumerable<double> values) {
     180      return Math.Sqrt(VariancePop(values));
     181    }
     182
     183    /// <summary>
     184    /// Calculates the sample variance of values. (sum (x - x_mean)² / (n-1))
    176185    /// </summary>
    177186    /// <param name="values"></param>
    178187    /// <returns></returns>
    179188    public static double Variance(this IEnumerable<double> values) {
     189      return Variance(values, true);
     190    }
     191
     192    /// <summary>
     193    /// Calculates the population variance of values. (sum (x - x_mean)² / n)
     194    /// </summary>
     195    /// <param name="values"></param>
     196    /// <returns></returns>
     197    public static double VariancePop(this IEnumerable<double> values) {
     198      return Variance(values, false);
     199    }
     200
     201    private static double Variance(IEnumerable<double> values, bool sampleVariance) {
    180202      int m_n = 0;
    181203      double m_oldM = 0.0;
     
    197219        }
    198220      }
    199       return ((m_n > 1) ? m_newS / (m_n - 1) : 0.0);
     221
     222      if (m_n == 0) return double.NaN;
     223      if (m_n == 1) return 0.0;
     224
     225      if (sampleVariance) return m_newS / (m_n - 1);
     226      else return m_newS / m_n;
    200227    }
    201228
Note: See TracChangeset for help on using the changeset viewer.