FBryant87
FBryant87

Reputation: 4615

C# Math.Net - Polynomial Fit 3rd order produces unexpected equation?

I have a graph with 4 points:

{0.0, 0.0}, {4687500.0, 10647580.9}, {4687500.1, 10647580.9}, {7500000.0, 10213609.9},

Using these points, in Excel I plot a 3rd order polynomial fit, which gives me the equation:

y = -4E-14x3 + 2E-07x2 + 1.5x + 2E+06

Which is perfect, and exactly what I need to draw the curve I'm after (the curve Excel draws is spot on).

However when I use the C# Math.Net library to plot a 3rd order polynomial fit using the exact same 4 points, I get a completely different set of coefficients (and therefore a hugely different equation and graph).

var coefficients = MathNet.Numerics.Fit.Polynomial(budgets, profits, 3);   

Any ideas why this is the case? The coefficients match perfectly when I use 2nd order, so I'm wondering if there's something special about the Math.Net 3rd order function.

The Excel curve rises, and later dips (what I'm after).

The Math.NET curve rises, dips, and then rises again towards the end.

EDIT: We are using 3rd order rather than 2nd order, because we need to keep 10647580.9 as the highest Y point when the curve is drawn.

Upvotes: 0

Views: 2772

Answers (1)

phv3773
phv3773

Reputation: 497

A comment for anyone who stumbles on this much later. This computation is at the limit of precision for either Excel or Numerics which is about 15 digits. A bit of imprecision results. When I reproduced the computation exactly in Math.Net, it ran okay, but when I divided all the numbers by 1,000, it crashed with a "Matrix must be positive definite" error.

Another example:

x = new double[] { 0.0, 1.0, 2.0, 3.0, 4.0 };
            y = new double[] { 10.0, 11.0, 12.0, 13.0, 14.0 };
            rslt = MathNet.Numerics.Fit.Polynomial(x, y, 3, DirectRegressionMethod.QR);
            Console.WriteLine("Test - QR");
            for (int i = 0; i < rslt.Length; i++) Console.WriteLine(i.ToString() + "  " + rslt[i].ToString());

returned

0  10
1  0.999999999999994
2  1.18687833744435E-15
3  0

I doubt that fitting a polynomial was the best solution for the OP. They are not as flexible as one might hope.

Upvotes: 2

Related Questions