View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements.  See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache License, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License.  You may obtain a copy of the License at
8    *
9    *      http://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  package org.apache.commons.math4.legacy.analysis.polynomials;
18  
19  import org.apache.commons.math4.legacy.analysis.differentiation.DerivativeStructure;
20  import org.apache.commons.math4.legacy.analysis.differentiation.UnivariateDifferentiableFunction;
21  import org.apache.commons.math4.legacy.exception.DimensionMismatchException;
22  import org.apache.commons.math4.legacy.exception.NoDataException;
23  import org.apache.commons.math4.legacy.exception.NullArgumentException;
24  import org.apache.commons.math4.legacy.exception.util.LocalizedFormats;
25  
26  /**
27   * Implements the representation of a real polynomial function in
28   * Newton Form. For reference, see <b>Elementary Numerical Analysis</b>,
29   * ISBN 0070124477, chapter 2.
30   * <p>
31   * The formula of polynomial in Newton form is
32   *     p(x) = a[0] + a[1](x-c[0]) + a[2](x-c[0])(x-c[1]) + ... +
33   *            a[n](x-c[0])(x-c[1])...(x-c[n-1])
34   * Note that the length of a[] is one more than the length of c[]</p>
35   *
36   * @since 1.2
37   */
38  public class PolynomialFunctionNewtonForm implements UnivariateDifferentiableFunction {
39  
40      /**
41       * The coefficients of the polynomial, ordered by degree -- i.e.
42       * coefficients[0] is the constant term and coefficients[n] is the
43       * coefficient of x^n where n is the degree of the polynomial.
44       */
45      private double[] coefficients;
46  
47      /**
48       * Centers of the Newton polynomial.
49       */
50      private final double[] c;
51  
52      /**
53       * When all c[i] = 0, a[] becomes normal polynomial coefficients,
54       * i.e. a[i] = coefficients[i].
55       */
56      private final double[] a;
57  
58      /**
59       * Whether the polynomial coefficients are available.
60       */
61      private boolean coefficientsComputed;
62  
63      /**
64       * Construct a Newton polynomial with the given a[] and c[]. The order of
65       * centers are important in that if c[] shuffle, then values of a[] would
66       * completely change, not just a permutation of old a[].
67       * <p>
68       * The constructor makes copy of the input arrays and assigns them.</p>
69       *
70       * @param a Coefficients in Newton form formula.
71       * @param c Centers.
72       * @throws NullArgumentException if any argument is {@code null}.
73       * @throws NoDataException if any array has zero length.
74       * @throws DimensionMismatchException if the size difference between
75       * {@code a} and {@code c} is not equal to 1.
76       */
77      public PolynomialFunctionNewtonForm(double[] a, double[] c)
78          throws NullArgumentException, NoDataException, DimensionMismatchException {
79  
80          verifyInputArray(a, c);
81          this.a = new double[a.length];
82          this.c = new double[c.length];
83          System.arraycopy(a, 0, this.a, 0, a.length);
84          System.arraycopy(c, 0, this.c, 0, c.length);
85          coefficientsComputed = false;
86      }
87  
88      /**
89       * Calculate the function value at the given point.
90       *
91       * @param z Point at which the function value is to be computed.
92       * @return the function value.
93       */
94      @Override
95      public double value(double z) {
96         return evaluate(a, c, z);
97      }
98  
99      /**
100      * {@inheritDoc}
101      * @since 3.1
102      */
103     @Override
104     public DerivativeStructure value(final DerivativeStructure t) {
105         verifyInputArray(a, c);
106 
107         final int n = c.length;
108         DerivativeStructure value = new DerivativeStructure(t.getFreeParameters(), t.getOrder(), a[n]);
109         for (int i = n - 1; i >= 0; i--) {
110             value = t.subtract(c[i]).multiply(value).add(a[i]);
111         }
112 
113         return value;
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.math4.legacy.analysis.interpolation.DividedDifferenceInterpolator#computeDividedDifference(double[],
230      * double[])
231      */
232     protected static void verifyInputArray(double[] a, double[] c)
233         throws NullArgumentException, NoDataException, DimensionMismatchException {
234         NullArgumentException.check(a);
235         NullArgumentException.check(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 }