FieldTrapezoidIntegrator.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.integration;

  22. import org.hipparchus.CalculusFieldElement;
  23. import org.hipparchus.Field;
  24. import org.hipparchus.exception.LocalizedCoreFormats;
  25. import org.hipparchus.exception.MathIllegalArgumentException;
  26. import org.hipparchus.exception.MathIllegalStateException;
  27. import org.hipparchus.util.FastMath;

  28. /**
  29.  * Implements the <a href="http://mathworld.wolfram.com/TrapezoidalRule.html">
  30.  * Trapezoid Rule</a> for integration of real univariate functions. For
  31.  * reference, see <b>Introduction to Numerical Analysis</b>, ISBN 038795452X,
  32.  * chapter 3.
  33.  * <p>
  34.  * The function should be integrable.</p>
  35.  * @param <T> Type of the field elements.
  36.  * @since 2.0
  37.  */
  38. public class FieldTrapezoidIntegrator<T extends CalculusFieldElement<T>> extends BaseAbstractFieldUnivariateIntegrator<T> {

  39.     /** Maximum number of iterations for trapezoid. */
  40.     public static final int TRAPEZOID_MAX_ITERATIONS_COUNT = 64;

  41.     /** Intermediate result. */
  42.     private T s;

  43.     /**
  44.      * Build a trapezoid integrator with given accuracies and iterations counts.
  45.      * @param field field to which function argument and value belong
  46.      * @param relativeAccuracy relative accuracy of the result
  47.      * @param absoluteAccuracy absolute accuracy of the result
  48.      * @param minimalIterationCount minimum number of iterations
  49.      * @param maximalIterationCount maximum number of iterations
  50.      * (must be less than or equal to {@link #TRAPEZOID_MAX_ITERATIONS_COUNT}
  51.      * @exception MathIllegalArgumentException if minimal number of iterations
  52.      * is not strictly positive
  53.      * @exception MathIllegalArgumentException if maximal number of iterations
  54.      * is lesser than or equal to the minimal number of iterations
  55.      * @exception MathIllegalArgumentException if maximal number of iterations
  56.      * is greater than {@link #TRAPEZOID_MAX_ITERATIONS_COUNT}
  57.      */
  58.     public FieldTrapezoidIntegrator(final Field<T> field,
  59.                                     final double relativeAccuracy,
  60.                                     final double absoluteAccuracy,
  61.                                     final int minimalIterationCount,
  62.                                     final int maximalIterationCount)
  63.         throws MathIllegalArgumentException {
  64.         super(field, relativeAccuracy, absoluteAccuracy, minimalIterationCount, maximalIterationCount);
  65.         if (maximalIterationCount > TRAPEZOID_MAX_ITERATIONS_COUNT) {
  66.             throw new MathIllegalArgumentException(LocalizedCoreFormats.NUMBER_TOO_LARGE_BOUND_EXCLUDED,
  67.                                                    maximalIterationCount, TRAPEZOID_MAX_ITERATIONS_COUNT);
  68.         }
  69.     }

  70.     /**
  71.      * Build a trapezoid integrator with given iteration counts.
  72.      * @param field field to which function argument and value belong
  73.      * @param minimalIterationCount minimum number of iterations
  74.      * @param maximalIterationCount maximum number of iterations
  75.      * (must be less than or equal to {@link #TRAPEZOID_MAX_ITERATIONS_COUNT}
  76.      * @exception MathIllegalArgumentException if minimal number of iterations
  77.      * is not strictly positive
  78.      * @exception MathIllegalArgumentException if maximal number of iterations
  79.      * is lesser than or equal to the minimal number of iterations
  80.      * @exception MathIllegalArgumentException if maximal number of iterations
  81.      * is greater than {@link #TRAPEZOID_MAX_ITERATIONS_COUNT}
  82.      */
  83.     public FieldTrapezoidIntegrator(final Field<T> field,
  84.                                     final int minimalIterationCount,
  85.                                     final int maximalIterationCount)
  86.         throws MathIllegalArgumentException {
  87.         super(field, minimalIterationCount, maximalIterationCount);
  88.         if (maximalIterationCount > TRAPEZOID_MAX_ITERATIONS_COUNT) {
  89.             throw new MathIllegalArgumentException(LocalizedCoreFormats.NUMBER_TOO_LARGE_BOUND_EXCLUDED,
  90.                                                    maximalIterationCount, TRAPEZOID_MAX_ITERATIONS_COUNT);
  91.         }
  92.     }

  93.     /**
  94.      * Construct a trapezoid integrator with default settings.
  95.      * @param field field to which function argument and value belong
  96.      * (max iteration count set to {@link #TRAPEZOID_MAX_ITERATIONS_COUNT})
  97.      */
  98.     public FieldTrapezoidIntegrator(final Field<T> field) {
  99.         super(field, DEFAULT_MIN_ITERATIONS_COUNT, TRAPEZOID_MAX_ITERATIONS_COUNT);
  100.     }

  101.     /**
  102.      * Compute the n-th stage integral of trapezoid rule. This function
  103.      * should only be called by API <code>integrate()</code> in the package.
  104.      * To save time it does not verify arguments - caller does.
  105.      * <p>
  106.      * The interval is divided equally into 2^n sections rather than an
  107.      * arbitrary m sections because this configuration can best utilize the
  108.      * already computed values.</p>
  109.      *
  110.      * @param baseIntegrator integrator holding integration parameters
  111.      * @param n the stage of 1/2 refinement, n = 0 is no refinement
  112.      * @return the value of n-th stage integral
  113.      * @throws MathIllegalStateException if the maximal number of evaluations
  114.      * is exceeded.
  115.      */
  116.     T stage(final BaseAbstractFieldUnivariateIntegrator<T> baseIntegrator, final int n)
  117.         throws MathIllegalStateException {

  118.         if (n == 0) {
  119.             final T max = baseIntegrator.getMax();
  120.             final T min = baseIntegrator.getMin();
  121.             s = max.subtract(min).multiply(0.5).
  122.                 multiply(baseIntegrator.computeObjectiveValue(min).
  123.                          add(baseIntegrator.computeObjectiveValue(max)));
  124.             return s;
  125.         } else {
  126.             final long np = 1L << (n-1);           // number of new points in this stage
  127.             T sum = getField().getZero();
  128.             final T max = baseIntegrator.getMax();
  129.             final T min = baseIntegrator.getMin();
  130.             // spacing between adjacent new points
  131.             final T spacing = max.subtract(min).divide(np);
  132.             T x = min.add(spacing.multiply(0.5));    // the first new point
  133.             for (long i = 0; i < np; i++) {
  134.                 sum = sum.add(baseIntegrator.computeObjectiveValue(x));
  135.                 x = x.add(spacing);
  136.             }
  137.             // add the new sum to previously calculated result
  138.             s = s.add(sum.multiply(spacing)).multiply(0.5);
  139.             return s;
  140.         }
  141.     }

  142.     /** {@inheritDoc} */
  143.     @Override
  144.     protected T doIntegrate()
  145.         throws MathIllegalArgumentException, MathIllegalStateException {

  146.         T oldt = stage(this, 0);
  147.         iterations.increment();
  148.         while (true) {
  149.             final int i = iterations.getCount();
  150.             final T t = stage(this, i);
  151.             if (i >= getMinimalIterationCount()) {
  152.                 final double delta  = FastMath.abs(t.subtract(oldt)).getReal();
  153.                 final double rlimit = FastMath.abs(oldt).add(FastMath.abs(t)).multiply(0.5 * getRelativeAccuracy()).getReal();
  154.                 if ((delta <= rlimit) || (delta <= getAbsoluteAccuracy())) {
  155.                     return t;
  156.                 }
  157.             }
  158.             oldt = t;
  159.             iterations.increment();
  160.         }

  161.     }

  162. }