Changeset 3984 for trunk/sources/HeuristicLab.Common
- Timestamp:
- 06/30/10 15:10:07 (14 years ago)
- File:
-
- 1 edited
Legend:
- Unmodified
- Added
- Removed
-
trunk/sources/HeuristicLab.Common/3.3/EnumerableStatisticExtensions.cs
r3742 r3984 67 67 /// <returns></returns> 68 68 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); 74 82 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; 84 86 } 85 87 } 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); 90 89 } 91 90 }
Note: See TracChangeset
for help on using the changeset viewer.