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    package org.apache.commons.math.analysis.polynomials;
018    
019    import org.apache.commons.math.DuplicateSampleAbscissaException;
020    import org.apache.commons.math.FunctionEvaluationException;
021    import org.apache.commons.math.MathRuntimeException;
022    import org.apache.commons.math.analysis.UnivariateRealFunction;
023    
024    /**
025     * Implements the representation of a real polynomial function in
026     * <a href="http://mathworld.wolfram.com/LagrangeInterpolatingPolynomial.html">
027     * Lagrange Form</a>. For reference, see <b>Introduction to Numerical
028     * Analysis</b>, ISBN 038795452X, chapter 2.
029     * <p>
030     * The approximated function should be smooth enough for Lagrange polynomial
031     * to work well. Otherwise, consider using splines instead.</p>
032     *
033     * @version $Revision: 799857 $ $Date: 2009-08-01 09:07:12 -0400 (Sat, 01 Aug 2009) $
034     * @since 1.2
035     */
036    public class PolynomialFunctionLagrangeForm implements UnivariateRealFunction {
037    
038        /**
039         * The coefficients of the polynomial, ordered by degree -- i.e.
040         * coefficients[0] is the constant term and coefficients[n] is the 
041         * coefficient of x^n where n is the degree of the polynomial.
042         */
043        private double coefficients[];
044    
045        /**
046         * Interpolating points (abscissas) and the function values at these points.
047         */
048        private double x[], y[];
049    
050        /**
051         * Whether the polynomial coefficients are available.
052         */
053        private boolean coefficientsComputed;
054    
055        /**
056         * Construct a Lagrange polynomial with the given abscissas and function
057         * values. The order of interpolating points are not important.
058         * <p>
059         * The constructor makes copy of the input arrays and assigns them.</p>
060         * 
061         * @param x interpolating points
062         * @param y function values at interpolating points
063         * @throws IllegalArgumentException if input arrays are not valid
064         */
065        public PolynomialFunctionLagrangeForm(double x[], double y[])
066            throws IllegalArgumentException {
067    
068            verifyInterpolationArray(x, y);
069            this.x = new double[x.length];
070            this.y = new double[y.length];
071            System.arraycopy(x, 0, this.x, 0, x.length);
072            System.arraycopy(y, 0, this.y, 0, y.length);
073            coefficientsComputed = false;
074        }
075    
076        /**
077         * Calculate the function value at the given point.
078         *
079         * @param z the point at which the function value is to be computed
080         * @return the function value
081         * @throws FunctionEvaluationException if a runtime error occurs
082         * @see UnivariateRealFunction#value(double)
083         */
084        public double value(double z) throws FunctionEvaluationException {
085            try {
086                return evaluate(x, y, z);
087            } catch (DuplicateSampleAbscissaException e) {
088                throw new FunctionEvaluationException(e, z, e.getPattern(), e.getArguments());
089            }
090        }
091    
092        /**
093         * Returns the degree of the polynomial.
094         * 
095         * @return the degree of the polynomial
096         */
097        public int degree() {
098            return x.length - 1;
099        }
100    
101        /**
102         * Returns a copy of the interpolating points array.
103         * <p>
104         * Changes made to the returned copy will not affect the polynomial.</p>
105         * 
106         * @return a fresh copy of the interpolating points array
107         */
108        public double[] getInterpolatingPoints() {
109            double[] out = new double[x.length];
110            System.arraycopy(x, 0, out, 0, x.length);
111            return out;
112        }
113    
114        /**
115         * Returns a copy of the interpolating values array.
116         * <p>
117         * Changes made to the returned copy will not affect the polynomial.</p>
118         * 
119         * @return a fresh copy of the interpolating values array
120         */
121        public double[] getInterpolatingValues() {
122            double[] out = new double[y.length];
123            System.arraycopy(y, 0, out, 0, y.length);
124            return out;
125        }
126    
127        /**
128         * Returns a copy of the coefficients array.
129         * <p>
130         * Changes made to the returned copy will not affect the polynomial.</p>
131         * 
132         * @return a fresh copy of the coefficients array
133         */
134        public double[] getCoefficients() {
135            if (!coefficientsComputed) {
136                computeCoefficients();
137            }
138            double[] out = new double[coefficients.length];
139            System.arraycopy(coefficients, 0, out, 0, coefficients.length);
140            return out;
141        }
142    
143        /**
144         * Evaluate the Lagrange polynomial using 
145         * <a href="http://mathworld.wolfram.com/NevillesAlgorithm.html">
146         * Neville's Algorithm</a>. It takes O(N^2) time.
147         * <p>
148         * This function is made public static so that users can call it directly
149         * without instantiating PolynomialFunctionLagrangeForm object.</p>
150         *
151         * @param x the interpolating points array
152         * @param y the interpolating values array
153         * @param z the point at which the function value is to be computed
154         * @return the function value
155         * @throws DuplicateSampleAbscissaException if the sample has duplicate abscissas
156         * @throws IllegalArgumentException if inputs are not valid
157         */
158        public static double evaluate(double x[], double y[], double z) throws
159            DuplicateSampleAbscissaException, IllegalArgumentException {
160    
161            int i, j, n, nearest = 0;
162            double value, c[], d[], tc, td, divider, w, dist, min_dist;
163    
164            verifyInterpolationArray(x, y);
165    
166            n = x.length;
167            c = new double[n];
168            d = new double[n];
169            min_dist = Double.POSITIVE_INFINITY;
170            for (i = 0; i < n; i++) {
171                // initialize the difference arrays
172                c[i] = y[i];
173                d[i] = y[i];
174                // find out the abscissa closest to z
175                dist = Math.abs(z - x[i]);
176                if (dist < min_dist) {
177                    nearest = i;
178                    min_dist = dist;
179                }
180            }
181    
182            // initial approximation to the function value at z
183            value = y[nearest];
184    
185            for (i = 1; i < n; i++) {
186                for (j = 0; j < n-i; j++) {
187                    tc = x[j] - z;
188                    td = x[i+j] - z;
189                    divider = x[j] - x[i+j];
190                    if (divider == 0.0) {
191                        // This happens only when two abscissas are identical.
192                        throw new DuplicateSampleAbscissaException(x[i], i, i+j);
193                    }
194                    // update the difference arrays
195                    w = (c[j+1] - d[j]) / divider;
196                    c[j] = tc * w;
197                    d[j] = td * w;
198                }
199                // sum up the difference terms to get the final value
200                if (nearest < 0.5*(n-i+1)) {
201                    value += c[nearest];    // fork down
202                } else {
203                    nearest--;
204                    value += d[nearest];    // fork up
205                }
206            }
207    
208            return value;
209        }
210    
211        /**
212         * Calculate the coefficients of Lagrange polynomial from the
213         * interpolation data. It takes O(N^2) time.
214         * <p>
215         * Note this computation can be ill-conditioned. Use with caution
216         * and only when it is necessary.</p>
217         *
218         * @throws ArithmeticException if any abscissas coincide
219         */
220        protected void computeCoefficients() throws ArithmeticException {
221            int i, j, n;
222            double c[], tc[], d, t;
223    
224            n = degree() + 1;
225            coefficients = new double[n];
226            for (i = 0; i < n; i++) {
227                coefficients[i] = 0.0;
228            }
229    
230            // c[] are the coefficients of P(x) = (x-x[0])(x-x[1])...(x-x[n-1])
231            c = new double[n+1];
232            c[0] = 1.0;
233            for (i = 0; i < n; i++) {
234                for (j = i; j > 0; j--) {
235                    c[j] = c[j-1] - c[j] * x[i];
236                }
237                c[0] *= (-x[i]);
238                c[i+1] = 1;
239            }
240    
241            tc = new double[n];
242            for (i = 0; i < n; i++) {
243                // d = (x[i]-x[0])...(x[i]-x[i-1])(x[i]-x[i+1])...(x[i]-x[n-1])
244                d = 1;
245                for (j = 0; j < n; j++) {
246                    if (i != j) {
247                        d *= (x[i] - x[j]);
248                    }
249                }
250                if (d == 0.0) {
251                    // This happens only when two abscissas are identical.
252                    for (int k = 0; k < n; ++k) {
253                        if ((i != k) && (x[i] == x[k])) {
254                            throw MathRuntimeException.createArithmeticException("identical abscissas x[{0}] == x[{1}] == {2} cause division by zero",
255                                                                                 i, k, x[i]);
256                        }
257                    }
258                }
259                t = y[i] / d;
260                // Lagrange polynomial is the sum of n terms, each of which is a
261                // polynomial of degree n-1. tc[] are the coefficients of the i-th
262                // numerator Pi(x) = (x-x[0])...(x-x[i-1])(x-x[i+1])...(x-x[n-1]).
263                tc[n-1] = c[n];     // actually c[n] = 1
264                coefficients[n-1] += t * tc[n-1];
265                for (j = n-2; j >= 0; j--) {
266                    tc[j] = c[j+1] + tc[j+1] * x[i];
267                    coefficients[j] += t * tc[j];
268                }
269            }
270    
271            coefficientsComputed = true;
272        }
273    
274        /**
275         * Verifies that the interpolation arrays are valid.
276         * <p>
277         * The interpolating points must be distinct. However it is not
278         * verified here, it is checked in evaluate() and computeCoefficients().</p>
279         * 
280         * @param x the interpolating points array
281         * @param y the interpolating values array
282         * @throws IllegalArgumentException if not valid
283         * @see #evaluate(double[], double[], double)
284         * @see #computeCoefficients()
285         */
286        public static void verifyInterpolationArray(double x[], double y[]) throws
287            IllegalArgumentException {
288    
289            if (Math.min(x.length, y.length) < 2) {
290                throw MathRuntimeException.createIllegalArgumentException(
291                      "{0} points are required, got only {1}",
292                      2, Math.min(x.length, y.length));
293            }
294            if (x.length != y.length) {
295                throw MathRuntimeException.createIllegalArgumentException(
296                      "dimension mismatch {0} != {1}", x.length, y.length);
297            }
298        }
299    }