4

Could anybody help me make a polynomial regression (order 2) with the Apache Math library.

The following data should give this equation: 39.79 x^2 - 497.66 x + 997.45 (computed by Excel with r2 = 0.9998)

// coding style from http://commons.apache.org/proper/commons-math/userguide/fitting.html    

double[] y = { 540.0, 160.0, -140.0, -360.0, -480.0, -560.0, -540.0, -440.0, -260.0, 0.0, 340.0};              
        final WeightedObservedPoints obs = new WeightedObservedPoints();
        for (double figure:y){
            obs.add(1.0, figure);
        }
        final PolynomialCurveFitter fitter = PolynomialCurveFitter.create(2);
        final double[] coeff = fitter.fit(obs.toList());
        System.out.println("coef="+Arrays.toString(coeff));

Here are the regression coefficients provided by the previous code:

coef=[-53.73522460839947, -52.22329678670934, -52.22329678670934]

Obviously, there's something I'm missing...

Thanks for your kind help

Dom

1 Answer 1

8

All your data points are at x = 1.

obs.add(1.0, figure);!!!!

instead of 1.0 there should be x value, if they are evenly spaced from zero than use for loop and ix instead of 1.0.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks. But according to the doc, the first item is the weight (" ...If no such information exist and all points should be treated the same, it is safe to put 1.0 as the weight for all points"). In addition, what do you call ix ? So I don't see your point.
acording to the doc add(x,y) == add(1.0, x,y) if you provide only two arguments the first is x value not the weight. Secondly, you should be worried yourself that you do regression without x values at all. As for ix, I mean it fyou have evenly spread points, the code would look like: for(int ix=0;ix<y.length;ix++) obs.add(ix,y[ix])
OK. Got it. You're absolutely right. That gives: coef=[997.45, -497.66, 39.79]. The last one for x^2, the middle one for x and the first one for the constant. Thanks a lot Zielu for your patience. I appreciate.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.