Apache Commons logo Commons Math

17 Curve Fitting

17.1 Overview

The fitting package deals with curve fitting for univariate real functions. When a univariate real function y = f(x) does depend on some unknown parameters p0, p1 ... pn-1, curve fitting can be used to find these parameters. It does this by fitting the curve so it remains very close to a set of observed points (x0, y0), (x1, y1) ... (xk-1, yk-1). This fitting is done by finding the parameters values that minimizes the objective function Σ(yi - f(xi))2. This is actually a least-squares problem.

For all provided curve fitters, the operating principle is the same. Users must first create an instance of the fitter, then add the observed points and once the complete sample of observed points has been added they must call the fit method which will compute the parameters that best fit the sample. A weight is associated with each observed point, this allows to take into account uncertainty on some points when they come from loosy measurements for example. 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.

17.2 General Case

The CurveFitter class provides curve fitting for general curves. Users must provide their own implementation of the curve template as a class implementing the ParametricUnivariateFunction interface and they must provide the initial guess of the parameters.

The following example shows how to fit data with a polynomial function.

final CurveFitter fitter = new CurveFitter(new LevenbergMarquardtOptimizer());
fitter.addObservedPoint(-1.00, 2.021170021833143);
fitter.addObservedPoint(-0.99, 2.221135431136975);
fitter.addObservedPoint(-0.98, 2.09985277659314);
fitter.addObservedPoint(-0.97, 2.0211192647627025);
// ... Lots of lines omitted ...
fitter.addObservedPoint( 0.99, -2.4345814727089854);

// The degree of the polynomial is deduced from the length of the array containing
// the initial guess for the coefficients of the polynomial.
final double[] init = { 12.9, -3.4, 2.1 }; // 12.9 - 3.4 x + 2.1 x^2

// Compute optimal coefficients.
final double[] best = fitter.fit(new PolynomialFunction.Parametric(), init);

// Construct the polynomial that best fits the data.
final PolynomialFunction fitted = new PolynomialFunction(best);
        

17.3 Special Cases

There are more specialized classes, for which the appropriate parametric function is implicitly used:

The HarmonicFitter and GaussianFitter also provide a no-argument fit() method that will internally estimate initial guess values for the parameters.