FieldMidPointIntegrator.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://en.wikipedia.org/wiki/Midpoint_method">
  30.  * Midpoint Rule</a> for integration of real univariate functions. For
  31.  * reference, see <b>Numerical Mathematics</b>, ISBN 0387989595,
  32.  * chapter 9.2.
  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 FieldMidPointIntegrator<T extends CalculusFieldElement<T>> extends BaseAbstractFieldUnivariateIntegrator<T> {

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

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

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

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

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

  123.         // number of new points in this stage
  124.         final long np = 1L << (n - 1);
  125.         T sum = getField().getZero();

  126.         // spacing between adjacent new points
  127.         final T spacing = diffMaxMin.divide(np);

  128.         // the first new point
  129.         T x = min.add(spacing.multiply(0.5));
  130.         for (long i = 0; i < np; i++) {
  131.             sum = sum.add(computeObjectiveValue(x));
  132.             x = x.add(spacing);
  133.         }
  134.         // add the new sum to previously calculated result
  135.         return previousStageResult.add(sum.multiply(spacing)).multiply(0.5);
  136.     }


  137.     /** {@inheritDoc} */
  138.     @Override
  139.     protected T doIntegrate()
  140.         throws MathIllegalArgumentException, MathIllegalStateException {

  141.         final T min = getMin();
  142.         final T diff = getMax().subtract(min);
  143.         final T midPoint = min.add(diff.multiply(0.5));

  144.         T oldt = diff.multiply(computeObjectiveValue(midPoint));

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

  158.     }

  159. }