BaseSecantSolver.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.  *      http://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. package org.apache.commons.math4.legacy.analysis.solvers;

  18. import org.apache.commons.math4.legacy.analysis.UnivariateFunction;
  19. import org.apache.commons.math4.legacy.exception.ConvergenceException;
  20. import org.apache.commons.math4.legacy.exception.MathInternalError;
  21. import org.apache.commons.math4.core.jdkmath.JdkMath;

  22. /**
  23.  * Base class for all bracketing <em>Secant</em>-based methods for root-finding
  24.  * (approximating a zero of a univariate real function).
  25.  *
  26.  * <p>Implementation of the {@link RegulaFalsiSolver <em>Regula Falsi</em>} and
  27.  * {@link IllinoisSolver <em>Illinois</em>} methods is based on the
  28.  * following article: M. Dowell and P. Jarratt,
  29.  * <em>A modified regula falsi method for computing the root of an
  30.  * equation</em>, BIT Numerical Mathematics, volume 11, number 2,
  31.  * pages 168-174, Springer, 1971.</p>
  32.  *
  33.  * <p>Implementation of the {@link PegasusSolver <em>Pegasus</em>} method is
  34.  * based on the following article: M. Dowell and P. Jarratt,
  35.  * <em>The "Pegasus" method for computing the root of an equation</em>,
  36.  * BIT Numerical Mathematics, volume 12, number 4, pages 503-508, Springer,
  37.  * 1972.</p>
  38.  *
  39.  * <p>The {@link SecantSolver <em>Secant</em>} method is <em>not</em> a
  40.  * bracketing method, so it is not implemented here. It has a separate
  41.  * implementation.</p>
  42.  *
  43.  * @since 3.0
  44.  */
  45. public abstract class BaseSecantSolver
  46.     extends AbstractUnivariateSolver
  47.     implements BracketedUnivariateSolver<UnivariateFunction> {

  48.     /** Default absolute accuracy. */
  49.     protected static final double DEFAULT_ABSOLUTE_ACCURACY = 1e-6;

  50.     /** The kinds of solutions that the algorithm may accept. */
  51.     private AllowedSolution allowed;

  52.     /** The <em>Secant</em>-based root-finding method to use. */
  53.     private final Method method;

  54.     /**
  55.      * Construct a solver.
  56.      *
  57.      * @param absoluteAccuracy Absolute accuracy.
  58.      * @param method <em>Secant</em>-based root-finding method to use.
  59.      */
  60.     protected BaseSecantSolver(final double absoluteAccuracy, final Method method) {
  61.         super(absoluteAccuracy);
  62.         this.allowed = AllowedSolution.ANY_SIDE;
  63.         this.method = method;
  64.     }

  65.     /**
  66.      * Construct a solver.
  67.      *
  68.      * @param relativeAccuracy Relative accuracy.
  69.      * @param absoluteAccuracy Absolute accuracy.
  70.      * @param method <em>Secant</em>-based root-finding method to use.
  71.      */
  72.     protected BaseSecantSolver(final double relativeAccuracy,
  73.                                final double absoluteAccuracy,
  74.                                final Method method) {
  75.         super(relativeAccuracy, absoluteAccuracy);
  76.         this.allowed = AllowedSolution.ANY_SIDE;
  77.         this.method = method;
  78.     }

  79.     /**
  80.      * Construct a solver.
  81.      *
  82.      * @param relativeAccuracy Maximum relative error.
  83.      * @param absoluteAccuracy Maximum absolute error.
  84.      * @param functionValueAccuracy Maximum function value error.
  85.      * @param method <em>Secant</em>-based root-finding method to use
  86.      */
  87.     protected BaseSecantSolver(final double relativeAccuracy,
  88.                                final double absoluteAccuracy,
  89.                                final double functionValueAccuracy,
  90.                                final Method method) {
  91.         super(relativeAccuracy, absoluteAccuracy, functionValueAccuracy);
  92.         this.allowed = AllowedSolution.ANY_SIDE;
  93.         this.method = method;
  94.     }

  95.     /** {@inheritDoc} */
  96.     @Override
  97.     public double solve(final int maxEval, final UnivariateFunction f,
  98.                         final double min, final double max,
  99.                         final AllowedSolution allowedSolution) {
  100.         return solve(maxEval, f, min, max, min + 0.5 * (max - min), allowedSolution);
  101.     }

  102.     /** {@inheritDoc} */
  103.     @Override
  104.     public double solve(final int maxEval, final UnivariateFunction f,
  105.                         final double min, final double max, final double startValue,
  106.                         final AllowedSolution allowedSolution) {
  107.         this.allowed = allowedSolution;
  108.         return super.solve(maxEval, f, min, max, startValue);
  109.     }

  110.     /** {@inheritDoc} */
  111.     @Override
  112.     public double solve(final int maxEval, final UnivariateFunction f,
  113.                         final double min, final double max, final double startValue) {
  114.         return solve(maxEval, f, min, max, startValue, AllowedSolution.ANY_SIDE);
  115.     }

  116.     /**
  117.      * {@inheritDoc}
  118.      *
  119.      * @throws ConvergenceException if the algorithm failed due to finite
  120.      * precision.
  121.      */
  122.     @Override
  123.     protected final double doSolve()
  124.         throws ConvergenceException {
  125.         // Get initial solution
  126.         double x0 = getMin();
  127.         double x1 = getMax();
  128.         double f0 = computeObjectiveValue(x0);
  129.         double f1 = computeObjectiveValue(x1);

  130.         // If one of the bounds is the exact root, return it. Since these are
  131.         // not under-approximations or over-approximations, we can return them
  132.         // regardless of the allowed solutions.
  133.         if (f0 == 0.0) {
  134.             return x0;
  135.         }
  136.         if (f1 == 0.0) {
  137.             return x1;
  138.         }

  139.         // Verify bracketing of initial solution.
  140.         verifyBracketing(x0, x1);

  141.         // Get accuracies.
  142.         final double ftol = getFunctionValueAccuracy();
  143.         final double atol = getAbsoluteAccuracy();
  144.         final double rtol = getRelativeAccuracy();

  145.         // Keep track of inverted intervals, meaning that the left bound is
  146.         // larger than the right bound.
  147.         boolean inverted = false;

  148.         // Keep finding better approximations.
  149.         while (true) {
  150.             // Calculate the next approximation.
  151.             final double x = x1 - ((f1 * (x1 - x0)) / (f1 - f0));
  152.             final double fx = computeObjectiveValue(x);

  153.             // If the new approximation is the exact root, return it. Since
  154.             // this is not an under-approximation or an over-approximation,
  155.             // we can return it regardless of the allowed solutions.
  156.             if (fx == 0.0) {
  157.                 return x;
  158.             }

  159.             // Update the bounds with the new approximation.
  160.             if (f1 * fx < 0) {
  161.                 // The value of x1 has switched to the other bound, thus inverting
  162.                 // the interval.
  163.                 x0 = x1;
  164.                 f0 = f1;
  165.                 inverted = !inverted;
  166.             } else {
  167.                 switch (method) {
  168.                 case ILLINOIS:
  169.                     f0 *= 0.5;
  170.                     break;
  171.                 case PEGASUS:
  172.                     f0 *= f1 / (f1 + fx);
  173.                     break;
  174.                 case REGULA_FALSI:
  175.                     // Detect early that algorithm is stuck, instead of waiting
  176.                     // for the maximum number of iterations to be exceeded.
  177.                     if (x == x1) {
  178.                         throw new ConvergenceException();
  179.                     }
  180.                     break;
  181.                 default:
  182.                     // Should never happen.
  183.                     throw new MathInternalError();
  184.                 }
  185.             }
  186.             // Update from [x0, x1] to [x0, x].
  187.             x1 = x;
  188.             f1 = fx;

  189.             // If the function value of the last approximation is too small,
  190.             // given the function value accuracy, then we can't get closer to
  191.             // the root than we already are.
  192.             if (JdkMath.abs(f1) <= ftol) {
  193.                 switch (allowed) {
  194.                 case ANY_SIDE:
  195.                     return x1;
  196.                 case LEFT_SIDE:
  197.                     if (inverted) {
  198.                         return x1;
  199.                     }
  200.                     break;
  201.                 case RIGHT_SIDE:
  202.                     if (!inverted) {
  203.                         return x1;
  204.                     }
  205.                     break;
  206.                 case BELOW_SIDE:
  207.                     if (f1 <= 0) {
  208.                         return x1;
  209.                     }
  210.                     break;
  211.                 case ABOVE_SIDE:
  212.                     if (f1 >= 0) {
  213.                         return x1;
  214.                     }
  215.                     break;
  216.                 default:
  217.                     throw new MathInternalError();
  218.                 }
  219.             }

  220.             // If the current interval is within the given accuracies, we
  221.             // are satisfied with the current approximation.
  222.             if (JdkMath.abs(x1 - x0) < JdkMath.max(rtol * JdkMath.abs(x1),
  223.                                                      atol)) {
  224.                 switch (allowed) {
  225.                 case ANY_SIDE:
  226.                     return x1;
  227.                 case LEFT_SIDE:
  228.                     return inverted ? x1 : x0;
  229.                 case RIGHT_SIDE:
  230.                     return inverted ? x0 : x1;
  231.                 case BELOW_SIDE:
  232.                     return (f1 <= 0) ? x1 : x0;
  233.                 case ABOVE_SIDE:
  234.                     return (f1 >= 0) ? x1 : x0;
  235.                 default:
  236.                     throw new MathInternalError();
  237.                 }
  238.             }
  239.         }
  240.     }

  241.     /** <em>Secant</em>-based root-finding methods. */
  242.     protected enum Method {

  243.         /**
  244.          * The {@link RegulaFalsiSolver <em>Regula Falsi</em>} or
  245.          * <em>False Position</em> method.
  246.          */
  247.         REGULA_FALSI,

  248.         /** The {@link IllinoisSolver <em>Illinois</em>} method. */
  249.         ILLINOIS,

  250.         /** The {@link PegasusSolver <em>Pegasus</em>} method. */
  251.         PEGASUS;
  252.     }
  253. }