Skip to content

Instantly share code, notes, and snippets.

@fauskanger
Last active December 10, 2019 09:53
Show Gist options
  • Save fauskanger/6120779 to your computer and use it in GitHub Desktop.
Save fauskanger/6120779 to your computer and use it in GitHub Desktop.
using System;
using MathNet.Numerics.LinearAlgebra.Double;
using MathNet.Numerics.LinearAlgebra.Double.Factorization;
namespace PolyRegressionCoefficients
{
class Program
{
public static void DrawRegression(double[] coeffs, double[] xList)
{
double xValue1 = xList[0];
double yValue1 = Polyval(coeffs, xList[0]);
double xValue2;
double yValue2;
for (int i = 1; i < xList.Length; i++)
{
xValue2 = xList[i];
yValue2 = Polyval(coeffs, xList[i]);
MyDrawLibrary.drawLine(xValue1, yValue1, xValue2, yValue2);
xValue1 = xValue2;
yValue1 = yValue2;
}
}
// From http://rosettacode.org/wiki/Polynomial_regression#C.23
public static double[] Polyfit(double[] x, double[] y, int degree)
{
// Vandermonde matrix
var v = new DenseMatrix(x.Length, degree + 1);
for (int i = 0; i < v.RowCount; i++)
for (int j = 0; j <= degree; j++) v[i, j] = Math.Pow(x[i], j);
var yv = new DenseVector(y).ToColumnMatrix();
QR qr = v.QR();
// Math.Net doesn't have an "economy" QR, so:
// cut R short to square upper triangle, then recompute Q
var r = qr.R.SubMatrix(0, degree + 1, 0, degree + 1);
var q = v.Multiply(r.Inverse());
var p = r.Inverse().Multiply(q.TransposeThisAndMultiply(yv));
return p.Column(0).ToArray();
}
public static double Polyval(double[] coeffs, double xValue)
{
double val = 0;
for (int i = 0; i < coeffs.Length; i++)
{
val += coeffs[i] * Math.Pow(xValue, i);
}
return val;
}
static void Main(string[] args)
{
double[] x = new[] { 0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0 };
double[] y = new[] { 1.0, 6.0, 17.0, 34.0, 57.0, 86.0, 121.0, 162.0, 209.0, 262.0, 321.0 };
double[] coefficients = Polyfit(x, y, 6);
DrawRegression(coefficients, x);
}
}
}
@fauskanger
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment