Reputation: 19
After using a few codes which are related to somekind of polyfit, I'm not having the succes i wanted. I have a few data points which always start in 0,0 and ends in 1,1. So I always should have a funtion which looks like this: hx^4 + ix^3 + jx^2 + kx. To check if the function is correct the sum of the coefficients should be 1. Using Excel with these data points and a trendline gives me this funtion:
y = -1,1094x^4 + 2,7022x^3 - 0,8903x^2 + 0,3024x.
No matter what i try i don't get these values with C# functions. These are the data points used to get the above function.
var x = new[] { 0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0 };
var y = new[] { 0.0, 0.364, 0.499, 0.596, 0.676, 0.746, 0.8, 0.853, 0.901, 0.949, 1.0 };
int order = 4;
The result I get from the all the function I used are the same:
x0 0,01647552447552759
x1 3,8548543123542967
x2 -8,747231934731909
x3 9,791958041958022
x4 -3,92482517482517
sum 0,9912307692307674
When comparing these in a chart they are in no way close to eachother. Does somebody know what method, code or library to use to get the right function from somekind of a polyfit?
the code used to get these values:
public static double[] Polyfit(double[] x, double[] y, int degree)
{
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<double> 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();
}
Another one i used is this one:
var x = new[] { 0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0 };
var y = new[] { 0.0, 0.364, 0.499, 0.596, 0.676, 0.746, 0.8, 0.853, 0.901, 0.949, 1.0 };
int order = 4;
var design = Matrix<double>.Build.Dense(x.Length, order + 1, (i, j) => Math.Pow(x[i], j));
double[] p = MultipleRegression.QR(design, Vector<double>.Build.Dense(y)).ToArray();
And the last one used is:
double[] p = Fit.Polynomial(x, y, order);
Upvotes: 0
Views: 271