001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.commons.math4.legacy.analysis.integration;
018
019import org.apache.commons.numbers.core.ArithmeticUtils;
020import org.apache.commons.math4.legacy.exception.NumberIsTooLargeException;
021import org.apache.commons.math4.core.jdkmath.JdkMath;
022
023/**
024 * Implements the <a href="https://en.wikipedia.org/wiki/Riemann_sum#Midpoint_rule">
025 * Midpoint Rule</a> for integration of real univariate functions. For
026 * reference, see <b>Numerical Mathematics</b>, ISBN 0387989595,
027 * chapter 9.2.
028 * <p>
029 * The function should be integrable.</p>
030 *
031 * @since 3.3
032 */
033public class MidPointIntegrator extends BaseAbstractUnivariateIntegrator {
034
035    /** Maximum number of iterations for midpoint. 39 = floor(log_3(2^63)), the
036     * maximum number of triplings allowed before exceeding 64-bit bounds.
037     */
038    private static final int MIDPOINT_MAX_ITERATIONS_COUNT = 39;
039
040    /**
041     * Build a midpoint integrator with given accuracies and iterations counts.
042     * @param relativeAccuracy relative accuracy of the result
043     * @param absoluteAccuracy absolute accuracy of the result
044     * @param minimalIterationCount minimum number of iterations
045     * @param maximalIterationCount maximum number of iterations
046     * @exception org.apache.commons.math4.legacy.exception.NotStrictlyPositiveException if minimal number of iterations
047     * is not strictly positive
048     * @exception org.apache.commons.math4.legacy.exception.NumberIsTooSmallException if maximal number of iterations
049     * is lesser than or equal to the minimal number of iterations
050     * @exception NumberIsTooLargeException if maximal number of iterations
051     * is greater than 39.
052     */
053    public MidPointIntegrator(final double relativeAccuracy,
054                              final double absoluteAccuracy,
055                              final int minimalIterationCount,
056                              final int maximalIterationCount) {
057        super(relativeAccuracy, absoluteAccuracy, minimalIterationCount, maximalIterationCount);
058        if (maximalIterationCount > MIDPOINT_MAX_ITERATIONS_COUNT) {
059            throw new NumberIsTooLargeException(maximalIterationCount,
060                                                MIDPOINT_MAX_ITERATIONS_COUNT, false);
061        }
062    }
063
064    /**
065     * Build a midpoint integrator with given iteration counts.
066     * @param minimalIterationCount minimum number of iterations
067     * @param maximalIterationCount maximum number of iterations
068     * @exception org.apache.commons.math4.legacy.exception.NotStrictlyPositiveException if minimal number of iterations
069     * is not strictly positive
070     * @exception org.apache.commons.math4.legacy.exception.NumberIsTooSmallException if maximal number of iterations
071     * is lesser than or equal to the minimal number of iterations
072     * @exception NumberIsTooLargeException if maximal number of iterations
073     * is greater than 39.
074     */
075    public MidPointIntegrator(final int minimalIterationCount,
076                              final int maximalIterationCount) {
077        super(minimalIterationCount, maximalIterationCount);
078        if (maximalIterationCount > MIDPOINT_MAX_ITERATIONS_COUNT) {
079            throw new NumberIsTooLargeException(maximalIterationCount,
080                                                MIDPOINT_MAX_ITERATIONS_COUNT, false);
081        }
082    }
083
084    /**
085     * Construct a midpoint integrator with default settings.
086     * (max iteration count set to {@link #MIDPOINT_MAX_ITERATIONS_COUNT})
087     */
088    public MidPointIntegrator() {
089        super(DEFAULT_MIN_ITERATIONS_COUNT, MIDPOINT_MAX_ITERATIONS_COUNT);
090    }
091
092    /**
093     * Compute the n-th stage integral of midpoint rule.
094     * This function should only be called by API <code>integrate()</code> in the package.
095     * To save time it does not verify arguments - caller does.
096     * <p>
097     * The interval is divided equally into 3^n sections rather than an
098     * arbitrary m sections because this configuration can best utilize the
099     * already computed values.</p>
100     *
101     * @param n the stage of 1/3 refinement. Must be larger than 0.
102     * @param previousStageResult Result from the previous call to the
103     * {@code stage} method.
104     * @param min Lower bound of the integration interval.
105     * @param diffMaxMin Difference between the lower bound and upper bound
106     * of the integration interval.
107     * @return the value of n-th stage integral
108     * @throws org.apache.commons.math4.legacy.exception.TooManyEvaluationsException if the maximal number of evaluations
109     * is exceeded.
110     */
111    private double stage(final int n,
112                         double previousStageResult,
113                         double min,
114                         double diffMaxMin) {
115        // number of points in the previous stage. This stage will contribute
116        // 2*3^{n-1} more points.
117        final long np = ArithmeticUtils.pow(3L, n - 1);
118        double sum = 0;
119
120        // spacing between adjacent new points
121        final double spacing = diffMaxMin / np;
122        final double leftOffset = spacing / 6;
123        final double rightOffset = 5 * leftOffset;
124
125        double x = min;
126        for (long i = 0; i < np; i++) {
127            // The first and second new points are located at the new midpoints
128            // generated when each previous integration slice is split into 3.
129            //
130            // |--------x--------|
131            // |--x--|--x--|--x--|
132            sum += computeObjectiveValue(x + leftOffset);
133            sum += computeObjectiveValue(x + rightOffset);
134            x += spacing;
135        }
136        // add the new sum to previously calculated result
137        return (previousStageResult + sum * spacing) / 3.0;
138    }
139
140
141    /** {@inheritDoc} */
142    @Override
143    protected double doIntegrate() {
144        final double min = getMin();
145        final double diff = getMax() - min;
146        final double midPoint = min + 0.5 * diff;
147
148        double oldt = diff * computeObjectiveValue(midPoint);
149
150        while (true) {
151            iterations.increment();
152            final int i = iterations.getCount();
153            final double t = stage(i, oldt, min, diff);
154            if (i >= getMinimalIterationCount()) {
155                final double delta = JdkMath.abs(t - oldt);
156                final double rLimit =
157                        getRelativeAccuracy() * (JdkMath.abs(oldt) + JdkMath.abs(t)) * 0.5;
158                if (delta <= rLimit || delta <= getAbsoluteAccuracy()) {
159                    return t;
160                }
161            }
162            oldt = t;
163        }
164    }
165}