Changeset 9706 for branches/StatisticalTesting/HeuristicLab.Analysis.Statistics/3.3/LinearLeastSquaresFitting.cs
- Timestamp:
- 07/15/13 16:33:13 (11 years ago)
- File:
-
- 1 edited
Legend:
- Unmodified
- Added
- Removed
-
branches/StatisticalTesting/HeuristicLab.Analysis.Statistics/3.3/LinearLeastSquaresFitting.cs
r9353 r9706 1 1 #region License Information 2 2 /* HeuristicLab 3 * Copyright (C) 2002-201 2Heuristic and Evolutionary Algorithms Laboratory (HEAL)3 * Copyright (C) 2002-2013 Heuristic and Evolutionary Algorithms Laboratory (HEAL) 4 4 * 5 5 * This file is part of HeuristicLab. … … 24 24 25 25 namespace HeuristicLab.Analysis.Statistics { 26 public class LinearLeastSquaresFitting { 27 public static void Calculate(double[] dataPoints, out double a1, out double a0) { 26 public class LinearLeastSquaresFitting : IFitting { 27 public void Calculate(double[] dataPoints, out double p0, out double p1) { 28 var stdX = Enumerable.Range(0, dataPoints.Count()).Select(x => (double)x).ToArray(); 29 Calculate(dataPoints, stdX, out p0, out p1); 30 } 31 32 public void Calculate(double[] y, double[] x, out double p0, out double p1) { 33 if (y.Count() != x.Count()) { 34 throw new ArgumentException("The lenght of x and y needs do be equal. "); 35 } 36 28 37 double sxy = 0.0; 29 38 double sxx = 0.0; 30 int n = dataPoints.Count();31 double sy = dataPoints.Sum();39 int n = y.Count(); 40 double sy = y.Sum(); 32 41 double sx = ((n - 1) * n) / 2; 33 42 double avgy = sy / n; … … 35 44 36 45 for (int i = 0; i < n; i++) { 37 sxy += i * dataPoints[i];38 sxx += i * i;46 sxy += x[i] * y[i]; 47 sxx += x[i] * x[i]; 39 48 } 40 49 41 a1= (sxy - (n * avgx * avgy)) / (sxx - (n * avgx * avgx));42 a0 = avgy - a1* avgx;50 p0 = (sxy - (n * avgx * avgy)) / (sxx - (n * avgx * avgx)); 51 p1 = avgy - p0 * avgx; 43 52 } 44 53 45 public static double CalculateError(double[] dataPoints, double a1, double a0) { 54 //TODO: adapt or remove 55 public double CalculateError(double[] dataPoints, double a1, double a0) { 46 56 double r = 0.0; 47 57 double avgy = dataPoints.Average(); … … 58 68 return r; 59 69 } 70 71 public DataRow CalculateFittedLine(double[] y, double[] x, string rowName) { 72 double k, d; 73 Calculate(y, x, out k, out d); 74 75 DataRow newRow = new DataRow(rowName); 76 for (int i = 0; i < x.Count(); i++) { 77 newRow.Values.Add(k * x[i] + d); 78 } 79 return newRow; 80 } 81 82 public DataRow CalculateFittedLine(double[] dataPoints, string rowName) { 83 DataRow newRow = new DataRow(rowName); 84 double c0, c1; 85 Calculate(dataPoints, out c0, out c1); 86 var stdX = Enumerable.Range(0, dataPoints.Count()).Select(x => (double)x).ToArray(); 87 88 for (int i = 0; i < stdX.Count(); i++) { 89 newRow.Values.Add(c0 * stdX[i] + c1); 90 } 91 92 return newRow; 93 } 94 95 public override string ToString() { 96 return "Linear Fitting"; 97 } 60 98 } 61 99 }
Note: See TracChangeset
for help on using the changeset viewer.