FieldPolynomialFunctionLagrangeForm.java

  1. /*
  2.  * Licensed to the Hipparchus project 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 Hipparchus project 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. package org.hipparchus.analysis.polynomials;

  18. import org.hipparchus.CalculusFieldElement;
  19. import org.hipparchus.Field;
  20. import org.hipparchus.analysis.CalculusFieldUnivariateFunction;
  21. import org.hipparchus.exception.LocalizedCoreFormats;
  22. import org.hipparchus.exception.MathIllegalArgumentException;
  23. import org.hipparchus.util.FastMath;
  24. import org.hipparchus.util.MathArrays;

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

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

  75.         MathArrays.checkEqualLength(x, y);
  76.         if (x.length < 2) {
  77.             throw new MathIllegalArgumentException(LocalizedCoreFormats.WRONG_NUMBER_OF_POINTS, 2, x.length, true);
  78.         }
  79.         MathArrays.checkOrder(x, MathArrays.OrderDirection.INCREASING, true, true);
  80.     }

  81.     /**
  82.      * Calculate the function value at the given point.
  83.      *
  84.      * @param z Point at which the function value is to be computed.
  85.      * @return the function value.
  86.      * @throws MathIllegalArgumentException if {@code x} and {@code y} have
  87.      * different lengths.
  88.      * @throws MathIllegalArgumentException
  89.      * if {@code x} is not sorted in strictly increasing order.
  90.      * @throws MathIllegalArgumentException if the size of {@code x} is less
  91.      * than 2.
  92.      */
  93.     @Override
  94.     public T value(final T z) {
  95.         int nearest = 0;
  96.         final int n = x.length;
  97.         final T[] c = y.clone();
  98.         final T[] d = c.clone();
  99.         double minDist = Double.POSITIVE_INFINITY;
  100.         for (int i = 0; i < n; i++) {
  101.             // find out the abscissa closest to z
  102.             final double dist = FastMath.abs(z.subtract(x[i])).getReal();
  103.             if (dist < minDist) {
  104.                 nearest = i;
  105.                 minDist = dist;
  106.             }
  107.         }

  108.         // initial approximation to the function value at z
  109.         T value = y[nearest];

  110.         for (int i = 1; i < n; i++) {
  111.             for (int j = 0; j < n-i; j++) {
  112.                 final T tc = x[j].subtract(z);
  113.                 final T td = x[i+j].subtract(z);
  114.                 final T divider = x[j].subtract(x[i+j]);
  115.                 // update the difference arrays
  116.                 final T w = (c[j+1].subtract(d[j])).divide(divider);
  117.                 c[j] = tc.multiply(w);
  118.                 d[j] = td.multiply(w);
  119.             }
  120.             // sum up the difference terms to get the final value
  121.             if (nearest < 0.5*(n-i+1)) {
  122.                 value = value.add(c[nearest]);    // fork down
  123.             } else {
  124.                 nearest--;
  125.                 value = value.add(d[nearest]);    // fork up
  126.             }
  127.         }

  128.         return value;
  129.     }

  130.     /**
  131.      * Returns the degree of the polynomial.
  132.      *
  133.      * @return the degree of the polynomial
  134.      */
  135.     public int degree() {
  136.         return x.length - 1;
  137.     }

  138.     /**
  139.      * Returns a copy of the interpolating points array.
  140.      * <p>
  141.      * Changes made to the returned copy will not affect the polynomial.</p>
  142.      *
  143.      * @return a fresh copy of the interpolating points array
  144.      */
  145.     public T[] getInterpolatingPoints() {
  146.         return x.clone();
  147.     }

  148.     /**
  149.      * Returns a copy of the interpolating values array.
  150.      * <p>
  151.      * Changes made to the returned copy will not affect the polynomial.</p>
  152.      *
  153.      * @return a fresh copy of the interpolating values array
  154.      */
  155.     public T[] getInterpolatingValues() {
  156.         return y.clone();
  157.     }

  158.     /**
  159.      * Returns a copy of the coefficients array.
  160.      * <p>
  161.      * Changes made to the returned copy will not affect the polynomial.</p>
  162.      * <p>
  163.      * Note that coefficients computation can be ill-conditioned. Use with caution
  164.      * and only when it is necessary.</p>
  165.      *
  166.      * @return a fresh copy of the coefficients array
  167.      */
  168.     public T[] getCoefficients() {
  169.         if (!coefficientsComputed) {
  170.             computeCoefficients();
  171.         }
  172.         return coefficients.clone();
  173.     }

  174.     /**
  175.      * Calculate the coefficients of Lagrange polynomial from the
  176.      * interpolation data. It takes O(n^2) time.
  177.      * Note that this computation can be ill-conditioned: Use with caution
  178.      * and only when it is necessary.
  179.      */
  180.     protected void computeCoefficients() {
  181.         final int n = degree() + 1;
  182.         final Field<T> field = x[0].getField();
  183.         coefficients = MathArrays.buildArray(field, n);

  184.         // c[] are the coefficients of P(x) = (x-x[0])(x-x[1])...(x-x[n-1])
  185.         final T[] c = MathArrays.buildArray(field, n + 1);
  186.         c[0] = field.getOne();
  187.         for (int i = 0; i < n; i++) {
  188.             for (int j = i; j > 0; j--) {
  189.                 c[j] = c[j-1].subtract(c[j].multiply(x[i]));
  190.             }
  191.             c[0] = c[0].multiply(x[i].negate());
  192.             c[i+1] = field.getOne();
  193.         }

  194.         final T[] tc = MathArrays.buildArray(field, n);
  195.         for (int i = 0; i < n; i++) {
  196.             // d = (x[i]-x[0])...(x[i]-x[i-1])(x[i]-x[i+1])...(x[i]-x[n-1])
  197.             T d = field.getOne();
  198.             for (int j = 0; j < n; j++) {
  199.                 if (i != j) {
  200.                     d = d.multiply(x[i].subtract(x[j]));
  201.                 }
  202.             }
  203.             final T t = y[i].divide(d);
  204.             // Lagrange polynomial is the sum of n terms, each of which is a
  205.             // polynomial of degree n-1. tc[] are the coefficients of the i-th
  206.             // numerator Pi(x) = (x-x[0])...(x-x[i-1])(x-x[i+1])...(x-x[n-1]).
  207.             tc[n-1] = c[n];     // actually c[n] = 1
  208.             coefficients[n-1] = coefficients[n-1].add(t.multiply(tc[n-1]));
  209.             for (int j = n-2; j >= 0; j--) {
  210.                 tc[j] = c[j+1].add(tc[j+1].multiply(x[i]));
  211.                 coefficients[j] = coefficients[j].add(t.multiply(tc[j]));
  212.             }
  213.         }

  214.         coefficientsComputed = true;
  215.     }
  216. }