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.numbers.arrays.SortInPlace; 20 import org.apache.commons.math4.legacy.analysis.UnivariateFunction; 21 import org.apache.commons.math4.legacy.exception.DimensionMismatchException; 22 import org.apache.commons.math4.legacy.exception.NonMonotonicSequenceException; 23 import org.apache.commons.math4.legacy.exception.NumberIsTooSmallException; 24 import org.apache.commons.math4.legacy.exception.util.LocalizedFormats; 25 import org.apache.commons.math4.core.jdkmath.JdkMath; 26 import org.apache.commons.math4.legacy.core.MathArrays; 27 28 /** 29 * Implements the representation of a real polynomial function in 30 * <a href="http://mathworld.wolfram.com/LagrangeInterpolatingPolynomial.html"> 31 * Lagrange Form</a>. For reference, see <b>Introduction to Numerical 32 * Analysis</b>, ISBN 038795452X, chapter 2. 33 * <p> 34 * The approximated function should be smooth enough for Lagrange polynomial 35 * to work well. Otherwise, consider using splines instead.</p> 36 * 37 * @since 1.2 38 */ 39 public class PolynomialFunctionLagrangeForm implements UnivariateFunction { 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 * Interpolating points (abscissas). 48 */ 49 private final double[] x; 50 /** 51 * Function values at interpolating points. 52 */ 53 private final double[] y; 54 /** 55 * Whether the polynomial coefficients are available. 56 */ 57 private boolean coefficientsComputed; 58 59 /** 60 * Construct a Lagrange polynomial with the given abscissas and function 61 * values. The order of interpolating points are not important. 62 * <p> 63 * The constructor makes copy of the input arrays and assigns them.</p> 64 * 65 * @param x interpolating points 66 * @param y function values at interpolating points 67 * @throws DimensionMismatchException if the array lengths are different. 68 * @throws NumberIsTooSmallException if the number of points is less than 2. 69 * @throws NonMonotonicSequenceException 70 * if two abscissae have the same value. 71 */ 72 public PolynomialFunctionLagrangeForm(double[] x, double[] y) 73 throws DimensionMismatchException, NumberIsTooSmallException, NonMonotonicSequenceException { 74 this.x = new double[x.length]; 75 this.y = new double[y.length]; 76 System.arraycopy(x, 0, this.x, 0, x.length); 77 System.arraycopy(y, 0, this.y, 0, y.length); 78 coefficientsComputed = false; 79 80 if (!verifyInterpolationArray(x, y, false)) { 81 SortInPlace.ASCENDING.apply(this.x, this.y); 82 // Second check in case some abscissa is duplicated. 83 verifyInterpolationArray(this.x, this.y, true); 84 } 85 } 86 87 /** 88 * Calculate the function value at the given point. 89 * 90 * @param z Point at which the function value is to be computed. 91 * @return the function value. 92 * @throws DimensionMismatchException if {@code x} and {@code y} have 93 * different lengths. 94 * @throws org.apache.commons.math4.legacy.exception.NonMonotonicSequenceException 95 * if {@code x} is not sorted in strictly increasing order. 96 * @throws NumberIsTooSmallException if the size of {@code x} is less 97 * than 2. 98 */ 99 @Override 100 public double value(double z) { 101 return evaluateInternal(x, y, z); 102 } 103 104 /** 105 * Returns the degree of the polynomial. 106 * 107 * @return the degree of the polynomial 108 */ 109 public int degree() { 110 return x.length - 1; 111 } 112 113 /** 114 * Returns a copy of the interpolating points array. 115 * <p> 116 * Changes made to the returned copy will not affect the polynomial.</p> 117 * 118 * @return a fresh copy of the interpolating points array 119 */ 120 public double[] getInterpolatingPoints() { 121 double[] out = new double[x.length]; 122 System.arraycopy(x, 0, out, 0, x.length); 123 return out; 124 } 125 126 /** 127 * Returns a copy of the interpolating values array. 128 * <p> 129 * Changes made to the returned copy will not affect the polynomial.</p> 130 * 131 * @return a fresh copy of the interpolating values array 132 */ 133 public double[] getInterpolatingValues() { 134 double[] out = new double[y.length]; 135 System.arraycopy(y, 0, out, 0, y.length); 136 return out; 137 } 138 139 /** 140 * Returns a copy of the coefficients array. 141 * <p> 142 * Changes made to the returned copy will not affect the polynomial.</p> 143 * <p> 144 * Note that coefficients computation can be ill-conditioned. Use with caution 145 * and only when it is necessary.</p> 146 * 147 * @return a fresh copy of the coefficients array 148 */ 149 public double[] getCoefficients() { 150 if (!coefficientsComputed) { 151 computeCoefficients(); 152 } 153 double[] out = new double[coefficients.length]; 154 System.arraycopy(coefficients, 0, out, 0, coefficients.length); 155 return out; 156 } 157 158 /** 159 * Evaluate the Lagrange polynomial using 160 * <a href="http://mathworld.wolfram.com/NevillesAlgorithm.html"> 161 * Neville's Algorithm</a>. It takes O(n^2) time. 162 * 163 * @param x Interpolating points array. 164 * @param y Interpolating values array. 165 * @param z Point at which the function value is to be computed. 166 * @return the function value. 167 * @throws DimensionMismatchException if {@code x} and {@code y} have 168 * different lengths. 169 * @throws NonMonotonicSequenceException 170 * if {@code x} is not sorted in strictly increasing order. 171 * @throws NumberIsTooSmallException if the size of {@code x} is less 172 * than 2. 173 */ 174 public static double evaluate(double[] x, double[] y, double z) 175 throws DimensionMismatchException, NumberIsTooSmallException, NonMonotonicSequenceException { 176 if (verifyInterpolationArray(x, y, false)) { 177 return evaluateInternal(x, y, z); 178 } 179 180 // Array is not sorted. 181 final double[] xNew = new double[x.length]; 182 final double[] yNew = new double[y.length]; 183 System.arraycopy(x, 0, xNew, 0, x.length); 184 System.arraycopy(y, 0, yNew, 0, y.length); 185 186 SortInPlace.ASCENDING.apply(xNew, yNew); 187 // Second check in case some abscissa is duplicated. 188 verifyInterpolationArray(xNew, yNew, true); 189 return evaluateInternal(xNew, yNew, z); 190 } 191 192 /** 193 * Evaluate the Lagrange polynomial using 194 * <a href="http://mathworld.wolfram.com/NevillesAlgorithm.html"> 195 * Neville's Algorithm</a>. It takes O(n^2) time. 196 * 197 * @param x Interpolating points array. 198 * @param y Interpolating values array. 199 * @param z Point at which the function value is to be computed. 200 * @return the function value. 201 * @throws DimensionMismatchException if {@code x} and {@code y} have 202 * different lengths. 203 * @throws org.apache.commons.math4.legacy.exception.NonMonotonicSequenceException 204 * if {@code x} is not sorted in strictly increasing order. 205 * @throws NumberIsTooSmallException if the size of {@code x} is less 206 * than 2. 207 */ 208 private static double evaluateInternal(double[] x, double[] y, double z) { 209 int nearest = 0; 210 final int n = x.length; 211 final double[] c = new double[n]; 212 final double[] d = new double[n]; 213 double minDist = Double.POSITIVE_INFINITY; 214 for (int i = 0; i < n; i++) { 215 // initialize the difference arrays 216 c[i] = y[i]; 217 d[i] = y[i]; 218 // find out the abscissa closest to z 219 final double dist = JdkMath.abs(z - x[i]); 220 if (dist < minDist) { 221 nearest = i; 222 minDist = dist; 223 } 224 } 225 226 // initial approximation to the function value at z 227 double value = y[nearest]; 228 229 for (int i = 1; i < n; i++) { 230 for (int j = 0; j < n-i; j++) { 231 final double tc = x[j] - z; 232 final double td = x[i+j] - z; 233 final double divider = x[j] - x[i+j]; 234 // update the difference arrays 235 final double w = (c[j+1] - d[j]) / divider; 236 c[j] = tc * w; 237 d[j] = td * w; 238 } 239 // sum up the difference terms to get the final value 240 if (nearest < 0.5*(n-i+1)) { 241 value += c[nearest]; // fork down 242 } else { 243 nearest--; 244 value += d[nearest]; // fork up 245 } 246 } 247 248 return value; 249 } 250 251 /** 252 * Calculate the coefficients of Lagrange polynomial from the 253 * interpolation data. It takes O(n^2) time. 254 * Note that this computation can be ill-conditioned: Use with caution 255 * and only when it is necessary. 256 */ 257 protected void computeCoefficients() { 258 final int n = degree() + 1; 259 coefficients = new double[n]; 260 for (int i = 0; i < n; i++) { 261 coefficients[i] = 0.0; 262 } 263 264 // c[] are the coefficients of P(x) = (x-x[0])(x-x[1])...(x-x[n-1]) 265 final double[] c = new double[n+1]; 266 c[0] = 1.0; 267 for (int i = 0; i < n; i++) { 268 for (int j = i; j > 0; j--) { 269 c[j] = c[j-1] - c[j] * x[i]; 270 } 271 c[0] *= -x[i]; 272 c[i+1] = 1; 273 } 274 275 final double[] tc = new double[n]; 276 for (int i = 0; i < n; i++) { 277 // d = (x[i]-x[0])...(x[i]-x[i-1])(x[i]-x[i+1])...(x[i]-x[n-1]) 278 double d = 1; 279 for (int j = 0; j < n; j++) { 280 if (i != j) { 281 d *= x[i] - x[j]; 282 } 283 } 284 final double t = y[i] / d; 285 // Lagrange polynomial is the sum of n terms, each of which is a 286 // polynomial of degree n-1. tc[] are the coefficients of the i-th 287 // numerator Pi(x) = (x-x[0])...(x-x[i-1])(x-x[i+1])...(x-x[n-1]). 288 tc[n-1] = c[n]; // actually c[n] = 1 289 coefficients[n-1] += t * tc[n-1]; 290 for (int j = n-2; j >= 0; j--) { 291 tc[j] = c[j+1] + tc[j+1] * x[i]; 292 coefficients[j] += t * tc[j]; 293 } 294 } 295 296 coefficientsComputed = true; 297 } 298 299 /** 300 * Check that the interpolation arrays are valid. 301 * The arrays features checked by this method are that both arrays have the 302 * same length and this length is at least 2. 303 * 304 * @param x Interpolating points array. 305 * @param y Interpolating values array. 306 * @param abort Whether to throw an exception if {@code x} is not sorted. 307 * @throws DimensionMismatchException if the array lengths are different. 308 * @throws NumberIsTooSmallException if the number of points is less than 2. 309 * @throws org.apache.commons.math4.legacy.exception.NonMonotonicSequenceException 310 * if {@code x} is not sorted in strictly increasing order and {@code abort} 311 * is {@code true}. 312 * @return {@code false} if the {@code x} is not sorted in increasing order, 313 * {@code true} otherwise. 314 * @see #evaluate(double[], double[], double) 315 * @see #computeCoefficients() 316 */ 317 public static boolean verifyInterpolationArray(double[] x, double[] y, boolean abort) 318 throws DimensionMismatchException, NumberIsTooSmallException, NonMonotonicSequenceException { 319 if (x.length != y.length) { 320 throw new DimensionMismatchException(x.length, y.length); 321 } 322 if (x.length < 2) { 323 throw new NumberIsTooSmallException(LocalizedFormats.WRONG_NUMBER_OF_POINTS, 2, x.length, true); 324 } 325 326 return MathArrays.checkOrder(x, MathArrays.OrderDirection.INCREASING, true, abort); 327 } 328 }