Free cookie consent management tool by TermsFeed Policy Generator

Changeset 3984


Ignore:
Timestamp:
06/30/10 15:10:07 (14 years ago)
Author:
gkronber
Message:

Changed implementation of extension method for the calculation of std. dev. of IEnumerable<double> to a routine which calculates the std. dev. in a single iteration over the enumerable. #938

File:
1 edited

Legend:

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

    r3742 r3984  
    6767    /// <returns></returns>
    6868    public static double Variance(this IEnumerable<double> values) {
    69       IList<double> list = values as IList<double>;
    70       if (list == null) {
    71         list = values.ToList();
    72       }
    73       if (list.Count == 0) throw new ArgumentException("Enumeration contains no elements.");
     69      int m_n = 0;
     70      double m_oldM = 0.0;
     71      double m_newM = 0.0;
     72      double m_oldS = 0.0;
     73      double m_newS = 0.0;
     74      foreach (double x in values) {
     75        m_n++;
     76        if (m_n == 1) {
     77          m_oldM = m_newM = x;
     78          m_oldS = 0.0;
     79        } else {
     80          m_newM = m_oldM + (x - m_oldM) / m_n;
     81          m_newS = m_oldS + (x - m_oldM) * (x - m_newM);
    7482
    75       double mean = list.Average();
    76       double squaredErrorsSum = 0.0;
    77       int n = list.Count;
    78       int s = 0;
    79       for (int i = 0; i < n; i++) {
    80         if (!double.IsNaN(list[i])) {
    81           double d = list[i] - mean;
    82           squaredErrorsSum += d * d;
    83           s++;
     83          // set up for next iteration
     84          m_oldM = m_newM;
     85          m_oldS = m_newS;
    8486        }
    8587      }
    86       if (s == 0) {
    87         throw new ArgumentException("Enumeration contains no non-NaN elements.");
    88       }
    89       return squaredErrorsSum / n;
     88      return ((m_n > 1) ? m_newS / (m_n - 1) : 0.0);
    9089    }
    9190  }
Note: See TracChangeset for help on using the changeset viewer.