0

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);
  • Can you post your C# code? – Neil Mar 15 '21 at 14:57
  • I have changed to artical – Zjwamerjong Mar 15 '21 at 15:11
  • "To check if the function is correct", what you mean is "To check if the function can accurately give f(1) = 1", other than that what does your definition of "correct" imply? There might be no way to get a 4th order function to precisely give all expected y values from the corresponding x value. – Lasse V. Karlsen Mar 16 '21 at 09:21
  • By saying 'to check if the functionn is correct' i do mean f(1) = 1. because the values are scaled to go through 1,1. If i use excel i get a 4th order function which is correct. but using C# i can't seem to get the same values. – Zjwamerjong Mar 17 '21 at 07:17

0 Answers0