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.math3.analysis.integration;
018
019import org.apache.commons.math3.exception.MathIllegalArgumentException;
020import org.apache.commons.math3.exception.MaxCountExceededException;
021import org.apache.commons.math3.exception.NotStrictlyPositiveException;
022import org.apache.commons.math3.exception.NumberIsTooLargeException;
023import org.apache.commons.math3.exception.NumberIsTooSmallException;
024import org.apache.commons.math3.exception.TooManyEvaluationsException;
025import org.apache.commons.math3.util.FastMath;
026
027/**
028 * Implements the <a href="http://en.wikipedia.org/wiki/Midpoint_method">
029 * Midpoint Rule</a> for integration of real univariate functions. For
030 * reference, see <b>Numerical Mathematics</b>, ISBN 0387989595,
031 * chapter 9.2.
032 * <p>
033 * The function should be integrable.</p>
034 *
035 * @since 3.3
036 */
037public class MidPointIntegrator extends BaseAbstractUnivariateIntegrator {
038
039    /** Maximum number of iterations for midpoint. */
040    public static final int MIDPOINT_MAX_ITERATIONS_COUNT = 64;
041
042    /**
043     * Build a midpoint integrator with given accuracies and iterations counts.
044     * @param relativeAccuracy relative accuracy of the result
045     * @param absoluteAccuracy absolute accuracy of the result
046     * @param minimalIterationCount minimum number of iterations
047     * @param maximalIterationCount maximum number of iterations
048     * (must be less than or equal to {@link #MIDPOINT_MAX_ITERATIONS_COUNT}
049     * @exception NotStrictlyPositiveException if minimal number of iterations
050     * is not strictly positive
051     * @exception NumberIsTooSmallException if maximal number of iterations
052     * is lesser than or equal to the minimal number of iterations
053     * @exception NumberIsTooLargeException if maximal number of iterations
054     * is greater than {@link #MIDPOINT_MAX_ITERATIONS_COUNT}
055     */
056    public MidPointIntegrator(final double relativeAccuracy,
057                              final double absoluteAccuracy,
058                              final int minimalIterationCount,
059                              final int maximalIterationCount)
060        throws NotStrictlyPositiveException, NumberIsTooSmallException, NumberIsTooLargeException {
061        super(relativeAccuracy, absoluteAccuracy, minimalIterationCount, maximalIterationCount);
062        if (maximalIterationCount > MIDPOINT_MAX_ITERATIONS_COUNT) {
063            throw new NumberIsTooLargeException(maximalIterationCount,
064                                                MIDPOINT_MAX_ITERATIONS_COUNT, false);
065        }
066    }
067
068    /**
069     * Build a midpoint integrator with given iteration counts.
070     * @param minimalIterationCount minimum number of iterations
071     * @param maximalIterationCount maximum number of iterations
072     * (must be less than or equal to {@link #MIDPOINT_MAX_ITERATIONS_COUNT}
073     * @exception NotStrictlyPositiveException if minimal number of iterations
074     * is not strictly positive
075     * @exception NumberIsTooSmallException if maximal number of iterations
076     * is lesser than or equal to the minimal number of iterations
077     * @exception NumberIsTooLargeException if maximal number of iterations
078     * is greater than {@link #MIDPOINT_MAX_ITERATIONS_COUNT}
079     */
080    public MidPointIntegrator(final int minimalIterationCount,
081                              final int maximalIterationCount)
082        throws NotStrictlyPositiveException, NumberIsTooSmallException, NumberIsTooLargeException {
083        super(minimalIterationCount, maximalIterationCount);
084        if (maximalIterationCount > MIDPOINT_MAX_ITERATIONS_COUNT) {
085            throw new NumberIsTooLargeException(maximalIterationCount,
086                                                MIDPOINT_MAX_ITERATIONS_COUNT, false);
087        }
088    }
089
090    /**
091     * Construct a midpoint integrator with default settings.
092     * (max iteration count set to {@link #MIDPOINT_MAX_ITERATIONS_COUNT})
093     */
094    public MidPointIntegrator() {
095        super(DEFAULT_MIN_ITERATIONS_COUNT, MIDPOINT_MAX_ITERATIONS_COUNT);
096    }
097
098    /**
099     * Compute the n-th stage integral of midpoint rule.
100     * This function should only be called by API <code>integrate()</code> in the package.
101     * To save time it does not verify arguments - caller does.
102     * <p>
103     * The interval is divided equally into 2^n sections rather than an
104     * arbitrary m sections because this configuration can best utilize the
105     * already computed values.</p>
106     *
107     * @param n the stage of 1/2 refinement. Must be larger than 0.
108     * @param previousStageResult Result from the previous call to the
109     * {@code stage} method.
110     * @param min Lower bound of the integration interval.
111     * @param diffMaxMin Difference between the lower bound and upper bound
112     * of the integration interval.
113     * @return the value of n-th stage integral
114     * @throws TooManyEvaluationsException if the maximal number of evaluations
115     * is exceeded.
116     */
117    private double stage(final int n,
118                         double previousStageResult,
119                         double min,
120                         double diffMaxMin)
121        throws TooManyEvaluationsException {
122
123        // number of new points in this stage
124        final long np = 1L << (n - 1);
125        double sum = 0;
126
127        // spacing between adjacent new points
128        final double spacing = diffMaxMin / np;
129
130        // the first new point
131        double x = min + 0.5 * spacing;
132        for (long i = 0; i < np; i++) {
133            sum += computeObjectiveValue(x);
134            x += spacing;
135        }
136        // add the new sum to previously calculated result
137        return 0.5 * (previousStageResult + sum * spacing);
138    }
139
140
141    /** {@inheritDoc} */
142    @Override
143    protected double doIntegrate()
144        throws MathIllegalArgumentException, TooManyEvaluationsException, MaxCountExceededException {
145
146        final double min = getMin();
147        final double diff = getMax() - min;
148        final double midPoint = min + 0.5 * diff;
149
150        double oldt = diff * computeObjectiveValue(midPoint);
151
152        while (true) {
153            incrementCount();
154            final int i = getIterations();
155            final double t = stage(i, oldt, min, diff);
156            if (i >= getMinimalIterationCount()) {
157                final double delta = FastMath.abs(t - oldt);
158                final double rLimit =
159                        getRelativeAccuracy() * (FastMath.abs(oldt) + FastMath.abs(t)) * 0.5;
160                if ((delta <= rLimit) || (delta <= getAbsoluteAccuracy())) {
161                    return t;
162                }
163            }
164            oldt = t;
165        }
166
167    }
168
169}