MidPointIntegrator.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://en.wikipedia.org/wiki/Midpoint_method">
  28.  * Midpoint Rule</a> for integration of real univariate functions. For
  29.  * reference, see <b>Numerical Mathematics</b>, ISBN 0387989595,
  30.  * chapter 9.2.
  31.  * <p>
  32.  * The function should be integrable.</p>
  33.  *
  34.  */
  35. public class MidPointIntegrator extends BaseAbstractUnivariateIntegrator {

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

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

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

  84.     /**
  85.      * Construct a midpoint integrator with default settings.
  86.      * (max iteration count set to {@link #MIDPOINT_MAX_ITERATIONS_COUNT})
  87.      */
  88.     public MidPointIntegrator() {
  89.         super(DEFAULT_MIN_ITERATIONS_COUNT, MIDPOINT_MAX_ITERATIONS_COUNT);
  90.     }

  91.     /**
  92.      * Compute the n-th stage integral of midpoint rule.
  93.      * This function should only be called by API <code>integrate()</code> in the package.
  94.      * To save time it does not verify arguments - caller does.
  95.      * <p>
  96.      * The interval is divided equally into 2^n sections rather than an
  97.      * arbitrary m sections because this configuration can best utilize the
  98.      * already computed values.</p>
  99.      *
  100.      * @param n the stage of 1/2 refinement. Must be larger than 0.
  101.      * @param previousStageResult Result from the previous call to the
  102.      * {@code stage} method.
  103.      * @param min Lower bound of the integration interval.
  104.      * @param diffMaxMin Difference between the lower bound and upper bound
  105.      * of the integration interval.
  106.      * @return the value of n-th stage integral
  107.      * @throws MathIllegalStateException if the maximal number of evaluations
  108.      * is exceeded.
  109.      */
  110.     private double stage(final int n,
  111.                          double previousStageResult,
  112.                          double min,
  113.                          double diffMaxMin)
  114.         throws MathIllegalStateException {

  115.         // number of new points in this stage
  116.         final long np = 1L << (n - 1);
  117.         double sum = 0;

  118.         // spacing between adjacent new points
  119.         final double spacing = diffMaxMin / np;

  120.         // the first new point
  121.         double x = min + 0.5 * spacing;
  122.         for (long i = 0; i < np; i++) {
  123.             sum += computeObjectiveValue(x);
  124.             x += spacing;
  125.         }
  126.         // add the new sum to previously calculated result
  127.         return 0.5 * (previousStageResult + sum * spacing);
  128.     }


  129.     /** {@inheritDoc} */
  130.     @Override
  131.     protected double doIntegrate()
  132.         throws MathIllegalArgumentException, MathIllegalStateException {

  133.         final double min = getMin();
  134.         final double diff = getMax() - min;
  135.         final double midPoint = min + 0.5 * diff;

  136.         double oldt = diff * computeObjectiveValue(midPoint);

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

  151.     }

  152. }