1. 程式人生 > >最小二乘法多項式曲線擬合原理與實現(錯誤地方已經修改底層補充自己寫的java實現)

最小二乘法多項式曲線擬合原理與實現(錯誤地方已經修改底層補充自己寫的java實現)

也可使用Apache開源庫commons math,提供的功能更強大,

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

package com.fjsh.algorithm.leastSquareMethod.deal;

import org.apache.commons.math3.fitting.PolynomialCurveFitter;
import org.apache.commons.math3.fitting.WeightedObservedPoints;

public class LeastSquareMethodFromApache {
	private static void testLeastSquareMethodFromApache() {  
        final WeightedObservedPoints obs = new WeightedObservedPoints();  
        obs.add(-3, 4);  
        obs.add(-2, 2);  
//        obs.add(-1, 3);  
//        obs.add(0, 0);  
//        obs.add(1, -1);  
//        obs.add(2, -2);  
//        obs.add(3, -5);  
  
        // Instantiate a third-degree polynomial fitter.  
        final PolynomialCurveFitter fitter = PolynomialCurveFitter.create(1);  
  
        // Retrieve fitted parameters (coefficients of the polynomial function).  
        final double[] coeff = fitter.fit(obs.toList());  
        for (double c : coeff) {  
            System.out.println(c);  
        }  
    }  


	/**
	 * 例如當引數是PolynomialCurveFitter.create(1);
	 * 點(-3, 4) (-2, 2) 此時擬合函式引數為-2,-2,公式為y=-2-2x;驗證符合
	 * @param args
	 */
	public static void main(String[] args) {
		testLeastSquareMethodFromApache();
	}
}