001    /*
002     * Licensed to the Apache Software Foundation (ASF) under one or more
003     * contributor license agreements.  See the NOTICE file distributed with
004     * this work for additional information regarding copyright ownership.
005     * The ASF licenses this file to You under the Apache License, Version 2.0
006     * (the "License"); you may not use this file except in compliance with
007     * the License.  You may obtain a copy of the License at
008     *
009     *      http://www.apache.org/licenses/LICENSE-2.0
010     *
011     * Unless required by applicable law or agreed to in writing, software
012     * distributed under the License is distributed on an "AS IS" BASIS,
013     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014     * See the License for the specific language governing permissions and
015     * limitations under the License.
016     */
017    
018    package org.apache.commons.math.optimization.fitting;
019    
020    import org.apache.commons.math.analysis.polynomials.PolynomialFunction;
021    import org.apache.commons.math.optimization.DifferentiableMultivariateVectorialOptimizer;
022    
023    /** This class implements a curve fitting specialized for polynomials.
024     * <p>Polynomial fitting is a very simple case of curve fitting. The
025     * estimated coefficients are the polynomial coefficients. They are
026     * searched by a least square estimator.</p>
027     * @version $Id: PolynomialFitter.java 1131229 2011-06-03 20:49:25Z luc $
028     * @since 2.0
029     */
030    
031    public class PolynomialFitter extends CurveFitter {
032        /** Polynomial degree. */
033        private final int degree;
034    
035        /**
036         * Simple constructor.
037         * <p>The polynomial fitter built this way are complete polynomials,
038         * ie. a n-degree polynomial has n+1 coefficients.</p>
039         *
040         * @param degree Maximal degree of the polynomial.
041         * @param optimizer Optimizer to use for the fitting.
042         */
043        public PolynomialFitter(int degree, final DifferentiableMultivariateVectorialOptimizer optimizer) {
044            super(optimizer);
045            this.degree = degree;
046        }
047    
048        /**
049         * Get the polynomial fitting the weighted (x, y) points.
050         *
051         * @return the coefficients of the polynomial that best fits the observed points.
052         * @throws org.apache.commons.math.exception.ConvergenceException
053         * if the algorithm failed to converge.
054         */
055        public double[] fit() {
056            return fit(new PolynomialFunction.Parametric(), new double[degree + 1]);
057        }
058    }