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.differentiation.DerivativeStructure;
020import org.apache.commons.math3.analysis.differentiation.UnivariateDifferentiableFunction;
021import org.apache.commons.math3.exception.DimensionMismatchException;
022import org.apache.commons.math3.exception.NoDataException;
023import org.apache.commons.math3.exception.NullArgumentException;
024import org.apache.commons.math3.exception.util.LocalizedFormats;
025import org.apache.commons.math3.util.MathUtils;
026
027/**
028 * Implements the representation of a real polynomial function in
029 * Newton Form. For reference, see <b>Elementary Numerical Analysis</b>,
030 * ISBN 0070124477, chapter 2.
031 * <p>
032 * The formula of polynomial in Newton form is
033 *     p(x) = a[0] + a[1](x-c[0]) + a[2](x-c[0])(x-c[1]) + ... +
034 *            a[n](x-c[0])(x-c[1])...(x-c[n-1])
035 * Note that the length of a[] is one more than the length of c[]</p>
036 *
037 * @since 1.2
038 */
039public class PolynomialFunctionNewtonForm implements UnivariateDifferentiableFunction {
040
041    /**
042     * The coefficients of the polynomial, ordered by degree -- i.e.
043     * coefficients[0] is the constant term and coefficients[n] is the
044     * coefficient of x^n where n is the degree of the polynomial.
045     */
046    private double coefficients[];
047
048    /**
049     * Centers of the Newton polynomial.
050     */
051    private final double c[];
052
053    /**
054     * When all c[i] = 0, a[] becomes normal polynomial coefficients,
055     * i.e. a[i] = coefficients[i].
056     */
057    private final double a[];
058
059    /**
060     * Whether the polynomial coefficients are available.
061     */
062    private boolean coefficientsComputed;
063
064    /**
065     * Construct a Newton polynomial with the given a[] and c[]. The order of
066     * centers are important in that if c[] shuffle, then values of a[] would
067     * completely change, not just a permutation of old a[].
068     * <p>
069     * The constructor makes copy of the input arrays and assigns them.</p>
070     *
071     * @param a Coefficients in Newton form formula.
072     * @param c Centers.
073     * @throws NullArgumentException if any argument is {@code null}.
074     * @throws NoDataException if any array has zero length.
075     * @throws DimensionMismatchException if the size difference between
076     * {@code a} and {@code c} is not equal to 1.
077     */
078    public PolynomialFunctionNewtonForm(double a[], double c[])
079        throws NullArgumentException, NoDataException, DimensionMismatchException {
080
081        verifyInputArray(a, c);
082        this.a = new double[a.length];
083        this.c = new double[c.length];
084        System.arraycopy(a, 0, this.a, 0, a.length);
085        System.arraycopy(c, 0, this.c, 0, c.length);
086        coefficientsComputed = false;
087    }
088
089    /**
090     * Calculate the function value at the given point.
091     *
092     * @param z Point at which the function value is to be computed.
093     * @return the function value.
094     */
095    public double value(double z) {
096       return evaluate(a, c, z);
097    }
098
099    /**
100     * {@inheritDoc}
101     * @since 3.1
102     */
103    public DerivativeStructure value(final DerivativeStructure t) {
104        verifyInputArray(a, c);
105
106        final int n = c.length;
107        DerivativeStructure value = new DerivativeStructure(t.getFreeParameters(), t.getOrder(), a[n]);
108        for (int i = n - 1; i >= 0; i--) {
109            value = t.subtract(c[i]).multiply(value).add(a[i]);
110        }
111
112        return value;
113
114    }
115
116    /**
117     * Returns the degree of the polynomial.
118     *
119     * @return the degree of the polynomial
120     */
121    public int degree() {
122        return c.length;
123    }
124
125    /**
126     * Returns a copy of coefficients in Newton form formula.
127     * <p>
128     * Changes made to the returned copy will not affect the polynomial.</p>
129     *
130     * @return a fresh copy of coefficients in Newton form formula
131     */
132    public double[] getNewtonCoefficients() {
133        double[] out = new double[a.length];
134        System.arraycopy(a, 0, out, 0, a.length);
135        return out;
136    }
137
138    /**
139     * Returns a copy of the centers array.
140     * <p>
141     * Changes made to the returned copy will not affect the polynomial.</p>
142     *
143     * @return a fresh copy of the centers array.
144     */
145    public double[] getCenters() {
146        double[] out = new double[c.length];
147        System.arraycopy(c, 0, out, 0, c.length);
148        return out;
149    }
150
151    /**
152     * Returns a copy of the coefficients array.
153     * <p>
154     * Changes made to the returned copy will not affect the polynomial.</p>
155     *
156     * @return a fresh copy of the coefficients array.
157     */
158    public double[] getCoefficients() {
159        if (!coefficientsComputed) {
160            computeCoefficients();
161        }
162        double[] out = new double[coefficients.length];
163        System.arraycopy(coefficients, 0, out, 0, coefficients.length);
164        return out;
165    }
166
167    /**
168     * Evaluate the Newton polynomial using nested multiplication. It is
169     * also called <a href="http://mathworld.wolfram.com/HornersRule.html">
170     * Horner's Rule</a> and takes O(N) time.
171     *
172     * @param a Coefficients in Newton form formula.
173     * @param c Centers.
174     * @param z Point at which the function value is to be computed.
175     * @return the function value.
176     * @throws NullArgumentException if any argument is {@code null}.
177     * @throws NoDataException if any array has zero length.
178     * @throws DimensionMismatchException if the size difference between
179     * {@code a} and {@code c} is not equal to 1.
180     */
181    public static double evaluate(double a[], double c[], double z)
182        throws NullArgumentException, DimensionMismatchException, NoDataException {
183        verifyInputArray(a, c);
184
185        final int n = c.length;
186        double value = a[n];
187        for (int i = n - 1; i >= 0; i--) {
188            value = a[i] + (z - c[i]) * value;
189        }
190
191        return value;
192    }
193
194    /**
195     * Calculate the normal polynomial coefficients given the Newton form.
196     * It also uses nested multiplication but takes O(N^2) time.
197     */
198    protected void computeCoefficients() {
199        final int n = degree();
200
201        coefficients = new double[n+1];
202        for (int i = 0; i <= n; i++) {
203            coefficients[i] = 0.0;
204        }
205
206        coefficients[0] = a[n];
207        for (int i = n-1; i >= 0; i--) {
208            for (int j = n-i; j > 0; j--) {
209                coefficients[j] = coefficients[j-1] - c[i] * coefficients[j];
210            }
211            coefficients[0] = a[i] - c[i] * coefficients[0];
212        }
213
214        coefficientsComputed = true;
215    }
216
217    /**
218     * Verifies that the input arrays are valid.
219     * <p>
220     * The centers must be distinct for interpolation purposes, but not
221     * for general use. Thus it is not verified here.</p>
222     *
223     * @param a the coefficients in Newton form formula
224     * @param c the centers
225     * @throws NullArgumentException if any argument is {@code null}.
226     * @throws NoDataException if any array has zero length.
227     * @throws DimensionMismatchException if the size difference between
228     * {@code a} and {@code c} is not equal to 1.
229     * @see org.apache.commons.math3.analysis.interpolation.DividedDifferenceInterpolator#computeDividedDifference(double[],
230     * double[])
231     */
232    protected static void verifyInputArray(double a[], double c[])
233        throws NullArgumentException, NoDataException, DimensionMismatchException {
234        MathUtils.checkNotNull(a);
235        MathUtils.checkNotNull(c);
236        if (a.length == 0 || c.length == 0) {
237            throw new NoDataException(LocalizedFormats.EMPTY_POLYNOMIALS_COEFFICIENTS_ARRAY);
238        }
239        if (a.length != c.length + 1) {
240            throw new DimensionMismatchException(LocalizedFormats.ARRAY_SIZES_SHOULD_HAVE_DIFFERENCE_1,
241                                                 a.length, c.length);
242        }
243    }
244
245}