    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     */
    017    package org.apache.commons.math.analysis.integration;
    018
    019    import org.apache.commons.math.FunctionEvaluationException;
    020    import org.apache.commons.math.MathRuntimeException;
    021    import org.apache.commons.math.MaxIterationsExceededException;
    022    import org.apache.commons.math.analysis.UnivariateRealFunction;
    023    import org.apache.commons.math.exception.util.LocalizedFormats;
    024    import org.apache.commons.math.util.FastMath;
    025
    026    /**
    027     * Implements the <a href="http://mathworld.wolfram.com/TrapezoidalRule.html">
    028     * Trapezoidal Rule</a> for integration of real univariate functions. For
    029     * reference, see <b>Introduction to Numerical Analysis</b>, ISBN 038795452X,
    030     * chapter 3.
    031     * <p>
    032     * The function should be integrable.</p>
    033     *
    034     * @version $Revision: 1070725 $ $Date: 2011-02-15 02:31:12 +0100 (mar. 15 f??vr. 2011) $
    035     * @since 1.2
    036     */
    037    public class TrapezoidIntegrator extends UnivariateRealIntegratorImpl {
    038
    039        /** Intermediate result. */
    040        private double s;
    041
    042        /**
    043         * Construct an integrator for the given function.
    044         *
    045         * @param f function to integrate
    046         * @deprecated as of 2.0 the integrand function is passed as an argument
    047         * to the {@link #integrate(UnivariateRealFunction, double, double)}method.
    048         */
    049        @Deprecated
    050        public TrapezoidIntegrator(UnivariateRealFunction f) {
    051            super(f, 64);
    052        }
    053
    054        /**
    055         * Construct an integrator.
    056         */
    057        public TrapezoidIntegrator() {
    058            super(64);
    059        }
    060
    061        /**
    062         * Compute the n-th stage integral of trapezoid rule. This function
    063         * should only be called by API <code>integrate()</code> in the package.
    064         * To save time it does not verify arguments - caller does.
    065         * <p>
    066         * The interval is divided equally into 2^n sections rather than an
    067         * arbitrary m sections because this configuration can best utilize the
    068         * alrealy computed values.</p>
    069         *
    070         * @param f the integrand function
    071         * @param min the lower bound for the interval
    072         * @param max the upper bound for the interval
    073         * @param n the stage of 1/2 refinement, n = 0 is no refinement
    074         * @return the value of n-th stage integral
    075         * @throws FunctionEvaluationException if an error occurs evaluating the function
    076         */
    077        double stage(final UnivariateRealFunction f,
    078                     final double min, final double max, final int n)
    079            throws FunctionEvaluationException {
    080
    081            if (n == 0) {
    082                s = 0.5 * (max - min) * (f.value(min) + f.value(max));
    083                return s;
    084            } else {
    085                final long np = 1L << (n-1);           // number of new points in this stage
    086                double sum = 0;
    087                final double spacing = (max - min) / np; // spacing between adjacent new points
    088                double x = min + 0.5 * spacing;    // the first new point
    089                for (long i = 0; i < np; i++) {
    090                    sum += f.value(x);
    091                    x += spacing;
    092                }
    093                // add the new sum to previously calculated result
    094                s = 0.5 * (s + sum * spacing);
    095                return s;
    096            }
    097        }
    098
    099        /** {@inheritDoc} */
    100        @Deprecated
    101        public double integrate(final double min, final double max)
    102            throws MaxIterationsExceededException, FunctionEvaluationException, IllegalArgumentException {
    103            return integrate(f, min, max);
    104        }
    105
    106        /** {@inheritDoc} */
    107        public double integrate(final UnivariateRealFunction f, final double min, final double max)
    108            throws MaxIterationsExceededException, FunctionEvaluationException, IllegalArgumentException {
    109
    110            clearResult();
    111            verifyInterval(min, max);
    112            verifyIterationCount();
    113
    114            double oldt = stage(f, min, max, 0);
    115            for (int i = 1; i <= maximalIterationCount; ++i) {
    116                final double t = stage(f, min, max, i);
    117                if (i >= minimalIterationCount) {
    118                    final double delta = FastMath.abs(t - oldt);
    119                    final double rLimit =
    120                        relativeAccuracy * (FastMath.abs(oldt) + FastMath.abs(t)) * 0.5;
    121                    if ((delta <= rLimit) || (delta <= absoluteAccuracy)) {
    122                        setResult(t, i);
    123                        return result;
    124                    }
    125                }
    126                oldt = t;
    127            }
    128            throw new MaxIterationsExceededException(maximalIterationCount);
    129        }
    130
    131        /** {@inheritDoc} */
    132        @Override
    133        protected void verifyIterationCount() throws IllegalArgumentException {
    134            super.verifyIterationCount();
    135            // at most 64 bisection refinements
    136            if (maximalIterationCount > 64) {
    137                throw MathRuntimeException.createIllegalArgumentException(
    138                        LocalizedFormats.INVALID_ITERATIONS_LIMITS,
    139                        0, 64);
    140            }
    141        }
    142    }