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