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.  *      https://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. /*
  18.  * This is not the original file distributed by the Apache Software Foundation
  19.  * It has been modified by the Hipparchus project
  20.  */

  21. package org.hipparchus.analysis.solvers;

  22. import org.hipparchus.analysis.UnivariateFunction;
  23. import org.hipparchus.exception.LocalizedCoreFormats;
  24. import org.hipparchus.exception.MathIllegalArgumentException;
  25. import org.hipparchus.exception.MathIllegalStateException;
  26. import org.hipparchus.exception.MathRuntimeException;
  27. import org.hipparchus.util.FastMath;

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

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

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

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

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

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

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

  100.     /** {@inheritDoc} */
  101.     @Override
  102.     public double solve(final int maxEval, final UnivariateFunction f,
  103.                         final double min, final double max,
  104.                         final AllowedSolution allowedSolution) {
  105.         return solve(maxEval, f, min, max, min + 0.5 * (max - min), allowedSolution);
  106.     }

  107.     /** {@inheritDoc} */
  108.     @Override
  109.     public double solve(final int maxEval, final UnivariateFunction f,
  110.                         final double min, final double max, final double startValue,
  111.                         final AllowedSolution allowedSolution) {
  112.         this.allowed = allowedSolution;
  113.         return super.solve(maxEval, f, min, max, startValue);
  114.     }

  115.     /** {@inheritDoc} */
  116.     @Override
  117.     public double solve(final int maxEval, final UnivariateFunction f,
  118.                         final double min, final double max, final double startValue) {
  119.         return solve(maxEval, f, min, max, startValue, AllowedSolution.ANY_SIDE);
  120.     }

  121.     /** {@inheritDoc} */
  122.     @Override
  123.     public Interval solveInterval(final int maxEval,
  124.                                   final UnivariateFunction f,
  125.                                   final double min,
  126.                                   final double max,
  127.                                   final double startValue) throws MathIllegalArgumentException, MathIllegalStateException {
  128.         setup(maxEval, f, min, max, startValue);
  129.         this.allowed = null;
  130.         return doSolveInterval();
  131.     }

  132.     /**
  133.      * {@inheritDoc}
  134.      *
  135.      * @throws MathIllegalStateException if the algorithm failed due to finite
  136.      * precision.
  137.      */
  138.     @Override
  139.     protected final double doSolve() throws MathIllegalStateException {
  140.         return doSolveInterval().getSide(allowed);
  141.     }

  142.     /**
  143.      * Find a root and return the containing interval.
  144.      *
  145.      * @return an interval containing the root such that the selected end point meets the
  146.      * convergence criteria.
  147.      * @throws MathIllegalStateException if convergence fails.
  148.      */
  149.     protected final Interval doSolveInterval() throws MathIllegalStateException {
  150.         // Get initial solution
  151.         double x0 = getMin();
  152.         double x1 = getMax();
  153.         double f0 = computeObjectiveValue(x0);
  154.         double f1 = computeObjectiveValue(x1);

  155.         // If one of the bounds is the exact root, return it. Since these are
  156.         // not under-approximations or over-approximations, we can return them
  157.         // regardless of the allowed solutions.
  158.         if (f0 == 0.0) {
  159.             return new Interval(x0, f0, x0, f0);
  160.         }
  161.         if (f1 == 0.0) {
  162.             return new Interval(x1, f1, x1, f1);
  163.         }

  164.         // Verify bracketing of initial solution.
  165.         verifyBracketing(x0, x1);

  166.         // Get accuracies.
  167.         final double ftol = getFunctionValueAccuracy();
  168.         final double atol = getAbsoluteAccuracy();
  169.         final double rtol = getRelativeAccuracy();

  170.         // Keep track of inverted intervals, meaning that the left bound is
  171.         // larger than the right bound.
  172.         boolean inverted = false;

  173.         // Keep finding better approximations.
  174.         while (true) {
  175.             // Calculate the next approximation.
  176.             final double x = x1 - ((f1 * (x1 - x0)) / (f1 - f0));
  177.             final double fx = computeObjectiveValue(x);

  178.             // If the new approximation is the exact root, return it. Since
  179.             // this is not an under-approximation or an over-approximation,
  180.             // we can return it regardless of the allowed solutions.
  181.             if (fx == 0.0) {
  182.                 return new Interval(x, fx, x, fx);
  183.             }

  184.             // Update the bounds with the new approximation.
  185.             if (f1 * fx < 0) {
  186.                 // The value of x1 has switched to the other bound, thus inverting
  187.                 // the interval.
  188.                 x0 = x1;
  189.                 f0 = f1;
  190.                 inverted = !inverted;
  191.             } else {
  192.                 switch (method) {
  193.                 case ILLINOIS:
  194.                     f0 *= 0.5;
  195.                     break;
  196.                 case PEGASUS:
  197.                     f0 *= f1 / (f1 + fx);
  198.                     break;
  199.                 case REGULA_FALSI:
  200.                     // Detect early that algorithm is stuck, instead of waiting
  201.                     // for the maximum number of iterations to be exceeded.
  202.                     if (x == x1) {
  203.                         throw new MathIllegalStateException(LocalizedCoreFormats.CONVERGENCE_FAILED);
  204.                     }
  205.                     break;
  206.                 default:
  207.                     // Should never happen.
  208.                     throw MathRuntimeException.createInternalError();
  209.                 }
  210.             }
  211.             // Update from [x0, x1] to [x0, x].
  212.             x1 = x;
  213.             f1 = fx;

  214.             // If the current interval is within the given accuracies, we
  215.             // are satisfied with the current approximation.
  216.             if (FastMath.abs(x1 - x0) < FastMath.max(rtol * FastMath.abs(x1), atol) ||
  217.                     (FastMath.abs(f1) < ftol && (allowed == AllowedSolution.ANY_SIDE  ||
  218.                             (inverted && allowed == AllowedSolution.LEFT_SIDE) ||
  219.                             (!inverted && allowed == AllowedSolution.RIGHT_SIDE) ||
  220.                             (f1 <= 0.0 && allowed == AllowedSolution.BELOW_SIDE) ||
  221.                             (f1 >= 0.0 && allowed == AllowedSolution.ABOVE_SIDE)))) {
  222.                 if (inverted) {
  223.                     return new Interval(x1, f1, x0, f0);
  224.                 } else {
  225.                     return new Interval(x0, f0, x1, f1);
  226.                 }
  227.             }
  228.         }
  229.     }

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

  232.         /**
  233.          * The {@link RegulaFalsiSolver <em>Regula Falsi</em>} or
  234.          * <em>False Position</em> method.
  235.          */
  236.         REGULA_FALSI,

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

  239.         /** The {@link PegasusSolver <em>Pegasus</em>} method. */
  240.         PEGASUS

  241.     }
  242. }