#region License Information /* HeuristicLab * Copyright (C) 2002-2013 Heuristic and Evolutionary Algorithms Laboratory (HEAL) * * This file is part of HeuristicLab. * * HeuristicLab is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * HeuristicLab is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with HeuristicLab. If not, see . */ #endregion using System; using System.Linq; namespace HeuristicLab.Analysis.AlgorithmBehavior.Analyzers { public class LinearLeastSquaresFitting { public static void Calculate(double[] dataPoints, out double a1, out double a0) { double sxy = 0.0; double sxx = 0.0; int n = dataPoints.Count(); double sy = dataPoints.Sum(); double sx = ((n - 1) * n) / 2; double avgy = sy / n; double avgx = sx / n; for (int i = 0; i < n; i++) { sxy += i * dataPoints[i]; sxx += i * i; } a1 = (sxy - (n * avgx * avgy)) / (sxx - (n * avgx * avgx)); a0 = avgy - a1 * avgx; } public static double CalculateError(double[] dataPoints, double a1, double a0) { double r = 0.0; double avgy = dataPoints.Average(); double sstot = 0.0; double sserr = 0.0; for (int i = 0; i < dataPoints.Count(); i++) { double y = a1 * i + a0; sstot += Math.Pow(dataPoints[i] - avgy, 2); sserr += Math.Pow(dataPoints[i] - y, 2); } r = 1.0 - (sserr / sstot); return r; } } }