/// <summary> /// Calculate line of best fit. /// </summary> /// <returns>The regression.</returns> /// <param name="x">The x coordinate.</param> /// <param name="y">The y coordinate.</param> /// I'm not going to try and explain linear regression in comments. /// Check out this link for more info: http://mathworld.wolfram.com/LeastSquaresFitting.html public static BestFit LinRegression(float[] x, float[] y) { if (x.Length != y.Length) { throw new Exception("Error: x-values and y-values must be of equal length!"); } //m = (n*sum(products) - sum(x's)sum(y's))/(n*sum(x squares) - sum(x's)^2) //Calculate: //1: The sum of the squares of the inputs. //2: The sum of the products of the inputs and outputs. float productSum = 0f; float productSquares = 0f; for (int a = 0; a < x.Length; a++) { productSum += x[a] * y[a]; productSquares += x[a] * x[a]; } //Calculus to solve for the line of best fit's slope. float dividend = (x.Length * productSum) - (Sum(x) * Sum(y)); float divisor = (x.Length * productSquares) - (float)Math.Pow(Sum(x), 2.0); float m = dividend / divisor; //Calculus to solve for the line of best fit's y-intercept. float b = (Sum(y) - m * (Sum(x))) / x.Length; //Return the result. LinearEquation eq = new LinearEquation(m, b); return(new BestFit(eq, x, y)); }
/// <summary> /// Calculate the exponential function of best fit and return it. /// </summary> /// <returns>The exponential function of best fit.</returns> /// <param name="x">The x inputs.</param> /// <param name="y">The y values.</param> /// For a clearer understanding of exponential regression, check out this /// link: http://mathworld.wolfram.com/LeastSquaresFittingExponential.html public static BestFit ExpRegression(float[] x, float[] y) { //Convert the line into a "linear" form. So it changes from //y = a * 10^bx to log(y) = log(a) + bx. Solve for the best fit of this "line". BestFit bestLin = LinRegression(x, Log(y)); //Convert to a linear equation. This will allow us to use the slope and //y-intercept in calculations. LinearEquation eq = (LinearEquation)bestLin.equation; //Find line of best fit for actual x-inputs and y-inputs. bestLin = LinRegression(x, y); //Looking at the equation from earlier, a is the y-intercept of the line. float A = ((LinearEquation)bestLin.equation).b; //The exponential equation should be in the form y = a * r^x. //From earlier, that means r = 10^b, which in this case makes r = 10^m float r = (float)Math.Pow(10, eq.m); //Return exponential equation. ExponentialEquation exp = new ExponentialEquation(A, r); return(new BestFit(exp, x, y)); }