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 */
017package org.apache.commons.math3.analysis.polynomials;
018
019import org.apache.commons.math3.analysis.UnivariateFunction;
020import org.apache.commons.math3.util.FastMath;
021import org.apache.commons.math3.util.MathArrays;
022import org.apache.commons.math3.exception.DimensionMismatchException;
023import org.apache.commons.math3.exception.NonMonotonicSequenceException;
024import org.apache.commons.math3.exception.NumberIsTooSmallException;
025import org.apache.commons.math3.exception.util.LocalizedFormats;
026
027/**
028 * Implements the representation of a real polynomial function in
029 * <a href="http://mathworld.wolfram.com/LagrangeInterpolatingPolynomial.html">
030 * Lagrange Form</a>. For reference, see <b>Introduction to Numerical
031 * Analysis</b>, ISBN 038795452X, chapter 2.
032 * <p>
033 * The approximated function should be smooth enough for Lagrange polynomial
034 * to work well. Otherwise, consider using splines instead.</p>
035 *
036 * @since 1.2
037 */
038public class PolynomialFunctionLagrangeForm implements UnivariateFunction {
039    /**
040     * The coefficients of the polynomial, ordered by degree -- i.e.
041     * coefficients[0] is the constant term and coefficients[n] is the
042     * coefficient of x^n where n is the degree of the polynomial.
043     */
044    private double coefficients[];
045    /**
046     * Interpolating points (abscissas).
047     */
048    private final double x[];
049    /**
050     * Function values at interpolating points.
051     */
052    private final double y[];
053    /**
054     * Whether the polynomial coefficients are available.
055     */
056    private boolean coefficientsComputed;
057
058    /**
059     * Construct a Lagrange polynomial with the given abscissas and function
060     * values. The order of interpolating points are not important.
061     * <p>
062     * The constructor makes copy of the input arrays and assigns them.</p>
063     *
064     * @param x interpolating points
065     * @param y function values at interpolating points
066     * @throws DimensionMismatchException if the array lengths are different.
067     * @throws NumberIsTooSmallException if the number of points is less than 2.
068     * @throws NonMonotonicSequenceException
069     * if two abscissae have the same value.
070     */
071    public PolynomialFunctionLagrangeForm(double x[], double y[])
072        throws DimensionMismatchException, NumberIsTooSmallException, NonMonotonicSequenceException {
073        this.x = new double[x.length];
074        this.y = new double[y.length];
075        System.arraycopy(x, 0, this.x, 0, x.length);
076        System.arraycopy(y, 0, this.y, 0, y.length);
077        coefficientsComputed = false;
078
079        if (!verifyInterpolationArray(x, y, false)) {
080            MathArrays.sortInPlace(this.x, this.y);
081            // Second check in case some abscissa is duplicated.
082            verifyInterpolationArray(this.x, this.y, true);
083        }
084    }
085
086    /**
087     * Calculate the function value at the given point.
088     *
089     * @param z Point at which the function value is to be computed.
090     * @return the function value.
091     * @throws DimensionMismatchException if {@code x} and {@code y} have
092     * different lengths.
093     * @throws org.apache.commons.math3.exception.NonMonotonicSequenceException
094     * if {@code x} is not sorted in strictly increasing order.
095     * @throws NumberIsTooSmallException if the size of {@code x} is less
096     * than 2.
097     */
098    public double value(double z) {
099        return evaluateInternal(x, y, z);
100    }
101
102    /**
103     * Returns the degree of the polynomial.
104     *
105     * @return the degree of the polynomial
106     */
107    public int degree() {
108        return x.length - 1;
109    }
110
111    /**
112     * Returns a copy of the interpolating points array.
113     * <p>
114     * Changes made to the returned copy will not affect the polynomial.</p>
115     *
116     * @return a fresh copy of the interpolating points array
117     */
118    public double[] getInterpolatingPoints() {
119        double[] out = new double[x.length];
120        System.arraycopy(x, 0, out, 0, x.length);
121        return out;
122    }
123
124    /**
125     * Returns a copy of the interpolating values array.
126     * <p>
127     * Changes made to the returned copy will not affect the polynomial.</p>
128     *
129     * @return a fresh copy of the interpolating values array
130     */
131    public double[] getInterpolatingValues() {
132        double[] out = new double[y.length];
133        System.arraycopy(y, 0, out, 0, y.length);
134        return out;
135    }
136
137    /**
138     * Returns a copy of the coefficients array.
139     * <p>
140     * Changes made to the returned copy will not affect the polynomial.</p>
141     * <p>
142     * Note that coefficients computation can be ill-conditioned. Use with caution
143     * and only when it is necessary.</p>
144     *
145     * @return a fresh copy of the coefficients array
146     */
147    public double[] getCoefficients() {
148        if (!coefficientsComputed) {
149            computeCoefficients();
150        }
151        double[] out = new double[coefficients.length];
152        System.arraycopy(coefficients, 0, out, 0, coefficients.length);
153        return out;
154    }
155
156    /**
157     * Evaluate the Lagrange polynomial using
158     * <a href="http://mathworld.wolfram.com/NevillesAlgorithm.html">
159     * Neville's Algorithm</a>. It takes O(n^2) time.
160     *
161     * @param x Interpolating points array.
162     * @param y Interpolating values array.
163     * @param z Point at which the function value is to be computed.
164     * @return the function value.
165     * @throws DimensionMismatchException if {@code x} and {@code y} have
166     * different lengths.
167     * @throws NonMonotonicSequenceException
168     * if {@code x} is not sorted in strictly increasing order.
169     * @throws NumberIsTooSmallException if the size of {@code x} is less
170     * than 2.
171     */
172    public static double evaluate(double x[], double y[], double z)
173        throws DimensionMismatchException, NumberIsTooSmallException, NonMonotonicSequenceException {
174        if (verifyInterpolationArray(x, y, false)) {
175            return evaluateInternal(x, y, z);
176        }
177
178        // Array is not sorted.
179        final double[] xNew = new double[x.length];
180        final double[] yNew = new double[y.length];
181        System.arraycopy(x, 0, xNew, 0, x.length);
182        System.arraycopy(y, 0, yNew, 0, y.length);
183
184        MathArrays.sortInPlace(xNew, yNew);
185        // Second check in case some abscissa is duplicated.
186        verifyInterpolationArray(xNew, yNew, true);
187        return evaluateInternal(xNew, yNew, z);
188    }
189
190    /**
191     * Evaluate the Lagrange polynomial using
192     * <a href="http://mathworld.wolfram.com/NevillesAlgorithm.html">
193     * Neville's Algorithm</a>. It takes O(n^2) time.
194     *
195     * @param x Interpolating points array.
196     * @param y Interpolating values array.
197     * @param z Point at which the function value is to be computed.
198     * @return the function value.
199     * @throws DimensionMismatchException if {@code x} and {@code y} have
200     * different lengths.
201     * @throws org.apache.commons.math3.exception.NonMonotonicSequenceException
202     * if {@code x} is not sorted in strictly increasing order.
203     * @throws NumberIsTooSmallException if the size of {@code x} is less
204     * than 2.
205     */
206    private static double evaluateInternal(double x[], double y[], double z) {
207        int nearest = 0;
208        final int n = x.length;
209        final double[] c = new double[n];
210        final double[] d = new double[n];
211        double min_dist = Double.POSITIVE_INFINITY;
212        for (int i = 0; i < n; i++) {
213            // initialize the difference arrays
214            c[i] = y[i];
215            d[i] = y[i];
216            // find out the abscissa closest to z
217            final double dist = FastMath.abs(z - x[i]);
218            if (dist < min_dist) {
219                nearest = i;
220                min_dist = dist;
221            }
222        }
223
224        // initial approximation to the function value at z
225        double value = y[nearest];
226
227        for (int i = 1; i < n; i++) {
228            for (int j = 0; j < n-i; j++) {
229                final double tc = x[j] - z;
230                final double td = x[i+j] - z;
231                final double divider = x[j] - x[i+j];
232                // update the difference arrays
233                final double w = (c[j+1] - d[j]) / divider;
234                c[j] = tc * w;
235                d[j] = td * w;
236            }
237            // sum up the difference terms to get the final value
238            if (nearest < 0.5*(n-i+1)) {
239                value += c[nearest];    // fork down
240            } else {
241                nearest--;
242                value += d[nearest];    // fork up
243            }
244        }
245
246        return value;
247    }
248
249    /**
250     * Calculate the coefficients of Lagrange polynomial from the
251     * interpolation data. It takes O(n^2) time.
252     * Note that this computation can be ill-conditioned: Use with caution
253     * and only when it is necessary.
254     */
255    protected void computeCoefficients() {
256        final int n = degree() + 1;
257        coefficients = new double[n];
258        for (int i = 0; i < n; i++) {
259            coefficients[i] = 0.0;
260        }
261
262        // c[] are the coefficients of P(x) = (x-x[0])(x-x[1])...(x-x[n-1])
263        final double[] c = new double[n+1];
264        c[0] = 1.0;
265        for (int i = 0; i < n; i++) {
266            for (int j = i; j > 0; j--) {
267                c[j] = c[j-1] - c[j] * x[i];
268            }
269            c[0] *= -x[i];
270            c[i+1] = 1;
271        }
272
273        final double[] tc = new double[n];
274        for (int i = 0; i < n; i++) {
275            // d = (x[i]-x[0])...(x[i]-x[i-1])(x[i]-x[i+1])...(x[i]-x[n-1])
276            double d = 1;
277            for (int j = 0; j < n; j++) {
278                if (i != j) {
279                    d *= x[i] - x[j];
280                }
281            }
282            final double t = y[i] / d;
283            // Lagrange polynomial is the sum of n terms, each of which is a
284            // polynomial of degree n-1. tc[] are the coefficients of the i-th
285            // numerator Pi(x) = (x-x[0])...(x-x[i-1])(x-x[i+1])...(x-x[n-1]).
286            tc[n-1] = c[n];     // actually c[n] = 1
287            coefficients[n-1] += t * tc[n-1];
288            for (int j = n-2; j >= 0; j--) {
289                tc[j] = c[j+1] + tc[j+1] * x[i];
290                coefficients[j] += t * tc[j];
291            }
292        }
293
294        coefficientsComputed = true;
295    }
296
297    /**
298     * Check that the interpolation arrays are valid.
299     * The arrays features checked by this method are that both arrays have the
300     * same length and this length is at least 2.
301     *
302     * @param x Interpolating points array.
303     * @param y Interpolating values array.
304     * @param abort Whether to throw an exception if {@code x} is not sorted.
305     * @throws DimensionMismatchException if the array lengths are different.
306     * @throws NumberIsTooSmallException if the number of points is less than 2.
307     * @throws org.apache.commons.math3.exception.NonMonotonicSequenceException
308     * if {@code x} is not sorted in strictly increasing order and {@code abort}
309     * is {@code true}.
310     * @return {@code false} if the {@code x} is not sorted in increasing order,
311     * {@code true} otherwise.
312     * @see #evaluate(double[], double[], double)
313     * @see #computeCoefficients()
314     */
315    public static boolean verifyInterpolationArray(double x[], double y[], boolean abort)
316        throws DimensionMismatchException, NumberIsTooSmallException, NonMonotonicSequenceException {
317        if (x.length != y.length) {
318            throw new DimensionMismatchException(x.length, y.length);
319        }
320        if (x.length < 2) {
321            throw new NumberIsTooSmallException(LocalizedFormats.WRONG_NUMBER_OF_POINTS, 2, x.length, true);
322        }
323
324        return MathArrays.checkOrder(x, MathArrays.OrderDirection.INCREASING, true, abort);
325    }
326}