PolynomialFunctionLagrangeForm.java

  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.  *      https://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. /*
  18.  * This is not the original file distributed by the Apache Software Foundation
  19.  * It has been modified by the Hipparchus project
  20.  */
  21. package org.hipparchus.analysis.polynomials;

  22. import org.hipparchus.analysis.UnivariateFunction;
  23. import org.hipparchus.exception.LocalizedCoreFormats;
  24. import org.hipparchus.exception.MathIllegalArgumentException;
  25. import org.hipparchus.util.FastMath;
  26. import org.hipparchus.util.MathArrays;

  27. /**
  28.  * Implements the representation of a real polynomial function in
  29.  * <a href="http://mathworld.wolfram.com/LagrangeInterpolatingPolynomial.html">
  30.  * Lagrange Form</a>. For reference, see <b>Introduction to Numerical
  31.  * Analysis</b>, ISBN 038795452X, chapter 2.
  32.  * <p>
  33.  * The approximated function should be smooth enough for Lagrange polynomial
  34.  * to work well. Otherwise, consider using splines instead.</p>
  35.  *
  36.  */
  37. public class PolynomialFunctionLagrangeForm implements UnivariateFunction {
  38.     /**
  39.      * The coefficients of the polynomial, ordered by degree -- i.e.
  40.      * coefficients[0] is the constant term and coefficients[n] is the
  41.      * coefficient of x^n where n is the degree of the polynomial.
  42.      */
  43.     private double[] coefficients;
  44.     /**
  45.      * Interpolating points (abscissas).
  46.      */
  47.     private final double[] x;
  48.     /**
  49.      * Function values at interpolating points.
  50.      */
  51.     private final double[] y;
  52.     /**
  53.      * Whether the polynomial coefficients are available.
  54.      */
  55.     private boolean coefficientsComputed;

  56.     /**
  57.      * Construct a Lagrange polynomial with the given abscissas and function
  58.      * values. The order of interpolating points are not important.
  59.      * <p>
  60.      * The constructor makes copy of the input arrays and assigns them.</p>
  61.      *
  62.      * @param x interpolating points
  63.      * @param y function values at interpolating points
  64.      * @throws MathIllegalArgumentException if the array lengths are different.
  65.      * @throws MathIllegalArgumentException if the number of points is less than 2.
  66.      * @throws MathIllegalArgumentException
  67.      * if two abscissae have the same value.
  68.      */
  69.     public PolynomialFunctionLagrangeForm(double[] x, double[] y)
  70.         throws MathIllegalArgumentException {
  71.         this.x = new double[x.length];
  72.         this.y = new double[y.length];
  73.         System.arraycopy(x, 0, this.x, 0, x.length);
  74.         System.arraycopy(y, 0, this.y, 0, y.length);
  75.         coefficientsComputed = false;

  76.         if (!verifyInterpolationArray(x, y, false)) {
  77.             MathArrays.sortInPlace(this.x, this.y);
  78.             // Second check in case some abscissa is duplicated.
  79.             verifyInterpolationArray(this.x, this.y, true);
  80.         }
  81.     }

  82.     /**
  83.      * Calculate the function value at the given point.
  84.      *
  85.      * @param z Point at which the function value is to be computed.
  86.      * @return the function value.
  87.      * @throws MathIllegalArgumentException if {@code x} and {@code y} have
  88.      * different lengths.
  89.      * @throws org.hipparchus.exception.MathIllegalArgumentException
  90.      * if {@code x} is not sorted in strictly increasing order.
  91.      * @throws MathIllegalArgumentException if the size of {@code x} is less
  92.      * than 2.
  93.      */
  94.     @Override
  95.     public double value(double z) {
  96.         return evaluateInternal(x, y, z);
  97.     }

  98.     /**
  99.      * Returns the degree of the polynomial.
  100.      *
  101.      * @return the degree of the polynomial
  102.      */
  103.     public int degree() {
  104.         return x.length - 1;
  105.     }

  106.     /**
  107.      * Returns a copy of the interpolating points array.
  108.      * <p>
  109.      * Changes made to the returned copy will not affect the polynomial.</p>
  110.      *
  111.      * @return a fresh copy of the interpolating points array
  112.      */
  113.     public double[] getInterpolatingPoints() {
  114.         double[] out = new double[x.length];
  115.         System.arraycopy(x, 0, out, 0, x.length);
  116.         return out;
  117.     }

  118.     /**
  119.      * Returns a copy of the interpolating values array.
  120.      * <p>
  121.      * Changes made to the returned copy will not affect the polynomial.</p>
  122.      *
  123.      * @return a fresh copy of the interpolating values array
  124.      */
  125.     public double[] getInterpolatingValues() {
  126.         double[] out = new double[y.length];
  127.         System.arraycopy(y, 0, out, 0, y.length);
  128.         return out;
  129.     }

  130.     /**
  131.      * Returns a copy of the coefficients array.
  132.      * <p>
  133.      * Changes made to the returned copy will not affect the polynomial.</p>
  134.      * <p>
  135.      * Note that coefficients computation can be ill-conditioned. Use with caution
  136.      * and only when it is necessary.</p>
  137.      *
  138.      * @return a fresh copy of the coefficients array
  139.      */
  140.     public double[] getCoefficients() {
  141.         if (!coefficientsComputed) {
  142.             computeCoefficients();
  143.         }
  144.         double[] out = new double[coefficients.length];
  145.         System.arraycopy(coefficients, 0, out, 0, coefficients.length);
  146.         return out;
  147.     }

  148.     /**
  149.      * Evaluate the Lagrange polynomial using
  150.      * <a href="http://mathworld.wolfram.com/NevillesAlgorithm.html">
  151.      * Neville's Algorithm</a>. It takes O(n^2) time.
  152.      *
  153.      * @param x Interpolating points array.
  154.      * @param y Interpolating values array.
  155.      * @param z Point at which the function value is to be computed.
  156.      * @return the function value.
  157.      * @throws MathIllegalArgumentException if {@code x} and {@code y} have
  158.      * different lengths.
  159.      * @throws MathIllegalArgumentException
  160.      * if {@code x} is not sorted in strictly increasing order.
  161.      * @throws MathIllegalArgumentException if the size of {@code x} is less
  162.      * than 2.
  163.      */
  164.     public static double evaluate(double[] x, double[] y, double z)
  165.         throws MathIllegalArgumentException {
  166.         if (verifyInterpolationArray(x, y, false)) {
  167.             return evaluateInternal(x, y, z);
  168.         }

  169.         // Array is not sorted.
  170.         final double[] xNew = new double[x.length];
  171.         final double[] yNew = new double[y.length];
  172.         System.arraycopy(x, 0, xNew, 0, x.length);
  173.         System.arraycopy(y, 0, yNew, 0, y.length);

  174.         MathArrays.sortInPlace(xNew, yNew);
  175.         // Second check in case some abscissa is duplicated.
  176.         verifyInterpolationArray(xNew, yNew, true);
  177.         return evaluateInternal(xNew, yNew, z);
  178.     }

  179.     /**
  180.      * Evaluate the Lagrange polynomial using
  181.      * <a href="http://mathworld.wolfram.com/NevillesAlgorithm.html">
  182.      * Neville's Algorithm</a>. It takes O(n^2) time.
  183.      *
  184.      * @param x Interpolating points array.
  185.      * @param y Interpolating values array.
  186.      * @param z Point at which the function value is to be computed.
  187.      * @return the function value.
  188.      * @throws MathIllegalArgumentException if {@code x} and {@code y} have
  189.      * different lengths.
  190.      * @throws org.hipparchus.exception.MathIllegalArgumentException
  191.      * if {@code x} is not sorted in strictly increasing order.
  192.      * @throws MathIllegalArgumentException if the size of {@code x} is less
  193.      * than 2.
  194.      */
  195.     private static double evaluateInternal(double[] x, double[] y, double z) {
  196.         int nearest = 0;
  197.         final int n = x.length;
  198.         final double[] c = new double[n];
  199.         final double[] d = new double[n];
  200.         double minDist = Double.POSITIVE_INFINITY;
  201.         for (int i = 0; i < n; i++) {
  202.             // initialize the difference arrays
  203.             c[i] = y[i];
  204.             d[i] = y[i];
  205.             // find out the abscissa closest to z
  206.             final double dist = FastMath.abs(z - x[i]);
  207.             if (dist < minDist) {
  208.                 nearest = i;
  209.                 minDist = dist;
  210.             }
  211.         }

  212.         // initial approximation to the function value at z
  213.         double value = y[nearest];

  214.         for (int i = 1; i < n; i++) {
  215.             for (int j = 0; j < n-i; j++) {
  216.                 final double tc = x[j] - z;
  217.                 final double td = x[i+j] - z;
  218.                 final double divider = x[j] - x[i+j];
  219.                 // update the difference arrays
  220.                 final double w = (c[j+1] - d[j]) / divider;
  221.                 c[j] = tc * w;
  222.                 d[j] = td * w;
  223.             }
  224.             // sum up the difference terms to get the final value
  225.             if (nearest < 0.5*(n-i+1)) {
  226.                 value += c[nearest];    // fork down
  227.             } else {
  228.                 nearest--;
  229.                 value += d[nearest];    // fork up
  230.             }
  231.         }

  232.         return value;
  233.     }

  234.     /**
  235.      * Calculate the coefficients of Lagrange polynomial from the
  236.      * interpolation data. It takes O(n^2) time.
  237.      * Note that this computation can be ill-conditioned: Use with caution
  238.      * and only when it is necessary.
  239.      */
  240.     protected void computeCoefficients() {
  241.         final int n = degree() + 1;
  242.         coefficients = new double[n];
  243.         for (int i = 0; i < n; i++) {
  244.             coefficients[i] = 0.0;
  245.         }

  246.         // c[] are the coefficients of P(x) = (x-x[0])(x-x[1])...(x-x[n-1])
  247.         final double[] c = new double[n+1];
  248.         c[0] = 1.0;
  249.         for (int i = 0; i < n; i++) {
  250.             for (int j = i; j > 0; j--) {
  251.                 c[j] = c[j-1] - c[j] * x[i];
  252.             }
  253.             c[0] *= -x[i];
  254.             c[i+1] = 1;
  255.         }

  256.         final double[] tc = new double[n];
  257.         for (int i = 0; i < n; i++) {
  258.             // d = (x[i]-x[0])...(x[i]-x[i-1])(x[i]-x[i+1])...(x[i]-x[n-1])
  259.             double d = 1;
  260.             for (int j = 0; j < n; j++) {
  261.                 if (i != j) {
  262.                     d *= x[i] - x[j];
  263.                 }
  264.             }
  265.             final double t = y[i] / d;
  266.             // Lagrange polynomial is the sum of n terms, each of which is a
  267.             // polynomial of degree n-1. tc[] are the coefficients of the i-th
  268.             // numerator Pi(x) = (x-x[0])...(x-x[i-1])(x-x[i+1])...(x-x[n-1]).
  269.             tc[n-1] = c[n];     // actually c[n] = 1
  270.             coefficients[n-1] += t * tc[n-1];
  271.             for (int j = n-2; j >= 0; j--) {
  272.                 tc[j] = c[j+1] + tc[j+1] * x[i];
  273.                 coefficients[j] += t * tc[j];
  274.             }
  275.         }

  276.         coefficientsComputed = true;
  277.     }

  278.     /**
  279.      * Check that the interpolation arrays are valid.
  280.      * The arrays features checked by this method are that both arrays have the
  281.      * same length and this length is at least 2.
  282.      *
  283.      * @param x Interpolating points array.
  284.      * @param y Interpolating values array.
  285.      * @param abort Whether to throw an exception if {@code x} is not sorted.
  286.      * @throws MathIllegalArgumentException if the array lengths are different.
  287.      * @throws MathIllegalArgumentException if the number of points is less than 2.
  288.      * @throws org.hipparchus.exception.MathIllegalArgumentException
  289.      * if {@code x} is not sorted in strictly increasing order and {@code abort}
  290.      * is {@code true}.
  291.      * @return {@code false} if the {@code x} is not sorted in increasing order,
  292.      * {@code true} otherwise.
  293.      * @see #evaluate(double[], double[], double)
  294.      * @see #computeCoefficients()
  295.      */
  296.     public static boolean verifyInterpolationArray(double[] x, double[] y, boolean abort)
  297.         throws MathIllegalArgumentException {
  298.         MathArrays.checkEqualLength(x, y);
  299.         if (x.length < 2) {
  300.             throw new MathIllegalArgumentException(LocalizedCoreFormats.WRONG_NUMBER_OF_POINTS, 2, x.length, true);
  301.         }

  302.         return MathArrays.checkOrder(x, MathArrays.OrderDirection.INCREASING, true, abort);
  303.     }
  304. }