TrapezoidIntegrator.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.exception.LocalizedCoreFormats;
  23. import org.hipparchus.exception.MathIllegalArgumentException;
  24. import org.hipparchus.exception.MathIllegalStateException;
  25. import org.hipparchus.util.FastMath;

  26. /**
  27.  * Implements the <a href="http://mathworld.wolfram.com/TrapezoidalRule.html">
  28.  * Trapezoid Rule</a> for integration of real univariate functions. For
  29.  * reference, see <b>Introduction to Numerical Analysis</b>, ISBN 038795452X,
  30.  * chapter 3.
  31.  * <p>
  32.  * The function should be integrable.</p>
  33.  *
  34.  */
  35. public class TrapezoidIntegrator extends BaseAbstractUnivariateIntegrator {

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

  38.     /** Intermediate result. */
  39.     private double s;

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

  65.     /**
  66.      * Build a trapezoid integrator with given iteration counts.
  67.      * @param minimalIterationCount minimum number of iterations
  68.      * @param maximalIterationCount maximum number of iterations
  69.      * (must be less than or equal to {@link #TRAPEZOID_MAX_ITERATIONS_COUNT}
  70.      * @exception MathIllegalArgumentException if minimal number of iterations
  71.      * is not strictly positive
  72.      * @exception MathIllegalArgumentException if maximal number of iterations
  73.      * is lesser than or equal to the minimal number of iterations
  74.      * @exception MathIllegalArgumentException if maximal number of iterations
  75.      * is greater than {@link #TRAPEZOID_MAX_ITERATIONS_COUNT}
  76.      */
  77.     public TrapezoidIntegrator(final int minimalIterationCount,
  78.                                final int maximalIterationCount)
  79.         throws MathIllegalArgumentException {
  80.         super(minimalIterationCount, maximalIterationCount);
  81.         if (maximalIterationCount > TRAPEZOID_MAX_ITERATIONS_COUNT) {
  82.             throw new MathIllegalArgumentException(LocalizedCoreFormats.NUMBER_TOO_LARGE_BOUND_EXCLUDED,
  83.                                                    maximalIterationCount, TRAPEZOID_MAX_ITERATIONS_COUNT);
  84.         }
  85.     }

  86.     /**
  87.      * Construct a trapezoid integrator with default settings.
  88.      * (max iteration count set to {@link #TRAPEZOID_MAX_ITERATIONS_COUNT})
  89.      */
  90.     public TrapezoidIntegrator() {
  91.         super(DEFAULT_MIN_ITERATIONS_COUNT, TRAPEZOID_MAX_ITERATIONS_COUNT);
  92.     }

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

  110.         if (n == 0) {
  111.             final double max = baseIntegrator.getMax();
  112.             final double min = baseIntegrator.getMin();
  113.             s = 0.5 * (max - min) *
  114.                       (baseIntegrator.computeObjectiveValue(min) +
  115.                        baseIntegrator.computeObjectiveValue(max));
  116.             return s;
  117.         } else {
  118.             final long np = 1L << (n-1);           // number of new points in this stage
  119.             double sum = 0;
  120.             final double max = baseIntegrator.getMax();
  121.             final double min = baseIntegrator.getMin();
  122.             // spacing between adjacent new points
  123.             final double spacing = (max - min) / np;
  124.             double x = min + 0.5 * spacing;    // the first new point
  125.             for (long i = 0; i < np; i++) {
  126.                 sum += baseIntegrator.computeObjectiveValue(x);
  127.                 x += spacing;
  128.             }
  129.             // add the new sum to previously calculated result
  130.             s = 0.5 * (s + sum * spacing);
  131.             return s;
  132.         }
  133.     }

  134.     /** {@inheritDoc} */
  135.     @Override
  136.     protected double doIntegrate()
  137.         throws MathIllegalArgumentException, MathIllegalStateException {

  138.         double oldt = stage(this, 0);
  139.         iterations.increment();
  140.         while (true) {
  141.             final int i = iterations.getCount();
  142.             final double t = stage(this, i);
  143.             if (i >= getMinimalIterationCount()) {
  144.                 final double delta = FastMath.abs(t - oldt);
  145.                 final double rLimit =
  146.                     getRelativeAccuracy() * (FastMath.abs(oldt) + FastMath.abs(t)) * 0.5;
  147.                 if ((delta <= rLimit) || (delta <= getAbsoluteAccuracy())) {
  148.                     return t;
  149.                 }
  150.             }
  151.             oldt = t;
  152.             iterations.increment();
  153.         }

  154.     }

  155. }