org.apache.commons.math3.exception.TooManyEvaluationsException Java Examples

The following examples show how to use org.apache.commons.math3.exception.TooManyEvaluationsException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: GaussNewtonOptimizerTest.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
@Test(expected=TooManyEvaluationsException.class)
public void testMaxEvaluations() throws Exception {
    CircleVectorial circle = new CircleVectorial();
    circle.addPoint( 30.0,  68.0);
    circle.addPoint( 50.0,  -6.0);
    circle.addPoint(110.0, -20.0);
    circle.addPoint( 35.0,  15.0);
    circle.addPoint( 45.0,  97.0);

    GaussNewtonOptimizer optimizer
        = new GaussNewtonOptimizer(new SimpleVectorValueChecker(1e-30, 1e-30));

    optimizer.optimize(new MaxEval(100),
                       circle.getModelFunction(),
                       circle.getModelFunctionJacobian(),
                       new Target(new double[] { 0, 0, 0, 0, 0 }),
                       new Weight(new double[] { 1, 1, 1, 1, 1 }),
                       new InitialGuess(new double[] { 98.680, 47.345 }));
}
 
Example #2
Source File: MidPointIntegrator.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Compute the n-th stage integral of midpoint rule.
 * This function should only be called by API <code>integrate()</code> in the package.
 * To save time it does not verify arguments - caller does.
 * <p>
 * The interval is divided equally into 2^n sections rather than an
 * arbitrary m sections because this configuration can best utilize the
 * already computed values.</p>
 *
 * @param n the stage of 1/2 refinement. Must be larger than 0.
 * @param previousStageResult Result from the previous call to the
 * {@code stage} method.
 * @param min Lower bound of the integration interval.
 * @param diffMaxMin Difference between the lower bound and upper bound
 * of the integration interval.
 * @return the value of n-th stage integral
 * @throws TooManyEvaluationsException if the maximal number of evaluations
 * is exceeded.
 */
private double stage(final int n,
                     double previousStageResult,
                     double min,
                     double diffMaxMin)
    throws TooManyEvaluationsException {

    // number of new points in this stage
    final long np = 1L << (n - 1);
    double sum = 0;

    // spacing between adjacent new points
    final double spacing = diffMaxMin / np;

    // the first new point
    double x = min + 0.5 * spacing;
    for (long i = 0; i < np; i++) {
        sum += computeObjectiveValue(x);
        x += spacing;
    }
    // add the new sum to previously calculated result
    return 0.5 * (previousStageResult + sum * spacing);
}
 
Example #3
Source File: NewtonSolver.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
protected double doSolve()
    throws TooManyEvaluationsException {
    final double startValue = getStartValue();
    final double absoluteAccuracy = getAbsoluteAccuracy();

    double x0 = startValue;
    double x1;
    while (true) {
        x1 = x0 - (computeObjectiveValue(x0) / computeDerivativeObjectiveValue(x0));
        if (FastMath.abs(x1 - x0) <= absoluteAccuracy) {
            return x1;
        }

        x0 = x1;
    }
}
 
Example #4
Source File: MinpackTest.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
private void minpackTest(MinpackFunction function, boolean exceptionExpected) {
    LevenbergMarquardtOptimizer optimizer
        = new LevenbergMarquardtOptimizer(FastMath.sqrt(2.22044604926e-16),
                                          FastMath.sqrt(2.22044604926e-16),
                                          2.22044604926e-16);
    try {
        PointVectorValuePair optimum
            = optimizer.optimize(new MaxEval(400 * (function.getN() + 1)),
                                 function.getModelFunction(),
                                 function.getModelFunctionJacobian(),
                                 new Target(function.getTarget()),
                                 new Weight(function.getWeight()),
                                 new InitialGuess(function.getStartPoint()));
        Assert.assertFalse(exceptionExpected);
        function.checkTheoreticalMinCost(optimizer.getRMS());
        function.checkTheoreticalMinParams(optimum);
    } catch (TooManyEvaluationsException e) {
        Assert.assertTrue(exceptionExpected);
    }
}
 
Example #5
Source File: BrentOptimizerTest.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void testSinMin() {
    UnivariateFunction f = new Sin();
    UnivariateOptimizer optimizer = new BrentOptimizer(1e-10, 1e-14);
    Assert.assertEquals(3 * Math.PI / 2, optimizer.optimize(200, f, GoalType.MINIMIZE, 4, 5).getPoint(), 1e-8);
    Assert.assertTrue(optimizer.getEvaluations() <= 50);
    Assert.assertEquals(200, optimizer.getMaxEvaluations());
    Assert.assertEquals(3 * Math.PI / 2, optimizer.optimize(200, f, GoalType.MINIMIZE, 1, 5).getPoint(), 1e-8);
    Assert.assertTrue(optimizer.getEvaluations() <= 100);
    Assert.assertTrue(optimizer.getEvaluations() >= 15);
    try {
        optimizer.optimize(10, f, GoalType.MINIMIZE, 4, 5);
        Assert.fail("an exception should have been thrown");
    } catch (TooManyEvaluationsException fee) {
        // expected
    }
}
 
Example #6
Source File: LegendreGaussIntegrator.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Compute the n-th stage integral.
 * @param n number of steps
 * @return the value of n-th stage integral
 * @throws TooManyEvaluationsException if the maximum number of evaluations
 * is exceeded.
 */
private double stage(final int n)
    throws TooManyEvaluationsException {

    // set up the step for the current stage
    final double step     = (getMax() - getMin()) / n;
    final double halfStep = step / 2.0;

    // integrate over all elementary steps
    double midPoint = getMin() + halfStep;
    double sum = 0.0;
    for (int i = 0; i < n; ++i) {
        for (int j = 0; j < abscissas.length; ++j) {
            sum += weights[j] * computeObjectiveValue(midPoint + halfStep * abscissas[j]);
        }
        midPoint += step;
    }

    return halfStep * sum;

}
 
Example #7
Source File: NewtonRaphsonSolver.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
protected double doSolve()
    throws TooManyEvaluationsException {
    final double startValue = getStartValue();
    final double absoluteAccuracy = getAbsoluteAccuracy();

    double x0 = startValue;
    double x1;
    while (true) {
        final DerivativeStructure y0 = computeObjectiveValueAndDerivative(x0);
        x1 = x0 - (y0.getValue() / y0.getPartialDerivative(1));
        if (FastMath.abs(x1 - x0) <= absoluteAccuracy) {
            return x1;
        }

        x0 = x1;
    }
}
 
Example #8
Source File: LaguerrePolynomialRealRootFinder.java    From Strata with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 * @throws MathException If there are no real roots; if the Commons method could not evaluate the function; if the Commons method could not converge.
 */
@Override
public Double[] getRoots(RealPolynomialFunction1D function) {
  ArgChecker.notNull(function, "function");
  try {
    Complex[] roots = ROOT_FINDER.solveAllComplex(function.getCoefficients(), 0);
    List<Double> realRoots = new ArrayList<>();
    for (Complex c : roots) {
      if (DoubleMath.fuzzyEquals(c.getImaginary(), 0d, EPS)) {
        realRoots.add(c.getReal());
      }
    }
    if (realRoots.isEmpty()) {
      throw new MathException("Could not find any real roots");
    }
    return realRoots.toArray(new Double[realRoots.size()]);
  } catch (TooManyEvaluationsException e) {
    throw new MathException(e);
  }
}
 
Example #9
Source File: GaussNewtonOptimizerTest.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
@Test(expected=TooManyEvaluationsException.class)
public void testMaxEvaluations() throws Exception {
    CircleVectorial circle = new CircleVectorial();
    circle.addPoint( 30.0,  68.0);
    circle.addPoint( 50.0,  -6.0);
    circle.addPoint(110.0, -20.0);
    circle.addPoint( 35.0,  15.0);
    circle.addPoint( 45.0,  97.0);

    GaussNewtonOptimizer optimizer
        = new GaussNewtonOptimizer(new SimpleVectorValueChecker(1e-30, 1e-30));

    optimizer.optimize(new MaxEval(100),
                       circle.getModelFunction(),
                       circle.getModelFunctionJacobian(),
                       new Target(new double[] { 0, 0, 0, 0, 0 }),
                       new Weight(new double[] { 1, 1, 1, 1, 1 }),
                       new InitialGuess(new double[] { 98.680, 47.345 }));
}
 
Example #10
Source File: BrentOptimizerTest.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void testQuinticMax() {
    // The quintic function has zeros at 0, +-0.5 and +-1.
    // The function has a local maximum at 0.27195613.
    UnivariateFunction f = new QuinticFunction();
    UnivariateOptimizer optimizer = new BrentOptimizer(1e-12, 1e-14);
    Assert.assertEquals(0.27195613, optimizer.optimize(new MaxEval(100),
                                                       new UnivariateObjectiveFunction(f),
                                                       GoalType.MAXIMIZE,
                                                       new SearchInterval(0.2, 0.3)).getPoint(), 1e-8);
    try {
        optimizer.optimize(new MaxEval(5),
                           new UnivariateObjectiveFunction(f),
                           GoalType.MAXIMIZE,
                           new SearchInterval(0.2, 0.3));
        Assert.fail("an exception should have been thrown");
    } catch (TooManyEvaluationsException miee) {
        // expected
    }
}
 
Example #11
Source File: MidPointIntegrator.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Compute the n-th stage integral of midpoint rule.
 * This function should only be called by API <code>integrate()</code> in the package.
 * To save time it does not verify arguments - caller does.
 * <p>
 * The interval is divided equally into 2^n sections rather than an
 * arbitrary m sections because this configuration can best utilize the
 * already computed values.</p>
 *
 * @param n the stage of 1/2 refinement. Must be larger than 0.
 * @param previousStageResult Result from the previous call to the
 * {@code stage} method.
 * @param min Lower bound of the integration interval.
 * @param diffMaxMin Difference between the lower bound and upper bound
 * of the integration interval.
 * @return the value of n-th stage integral
 * @throws TooManyEvaluationsException if the maximal number of evaluations
 * is exceeded.
 */
private double stage(final int n,
                     double previousStageResult,
                     double min,
                     double diffMaxMin)
    throws TooManyEvaluationsException {

    // number of new points in this stage
    final long np = 1L << (n - 1);
    double sum = 0;

    // spacing between adjacent new points
    final double spacing = diffMaxMin / np;

    // the first new point
    double x = min + 0.5 * spacing;
    for (long i = 0; i < np; i++) {
        sum += computeObjectiveValue(x);
        x += spacing;
    }
    // add the new sum to previously calculated result
    return 0.5 * (previousStageResult + sum * spacing);
}
 
Example #12
Source File: GaussNewtonOptimizerTest.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
@Test(expected=TooManyEvaluationsException.class)
public void testMaxEvaluations() throws Exception {
    CircleVectorial circle = new CircleVectorial();
    circle.addPoint( 30.0,  68.0);
    circle.addPoint( 50.0,  -6.0);
    circle.addPoint(110.0, -20.0);
    circle.addPoint( 35.0,  15.0);
    circle.addPoint( 45.0,  97.0);

    GaussNewtonOptimizer optimizer
        = new GaussNewtonOptimizer(new SimpleVectorValueChecker(1.0e-30, 1.0e-30));

    optimizer.optimize(100, circle, new double[] { 0, 0, 0, 0, 0 },
                       new double[] { 1, 1, 1, 1, 1 },
                       new double[] { 98.680, 47.345 });
}
 
Example #13
Source File: GaussNewtonOptimizerTest.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
@Test(expected=TooManyEvaluationsException.class)
public void testMaxEvaluations() throws Exception {
    CircleVectorial circle = new CircleVectorial();
    circle.addPoint( 30.0,  68.0);
    circle.addPoint( 50.0,  -6.0);
    circle.addPoint(110.0, -20.0);
    circle.addPoint( 35.0,  15.0);
    circle.addPoint( 45.0,  97.0);

    GaussNewtonOptimizer optimizer
        = new GaussNewtonOptimizer(new SimpleVectorValueChecker(1.0e-30, 1.0e-30));

    optimizer.optimize(100, circle, new double[] { 0, 0, 0, 0, 0 },
                       new double[] { 1, 1, 1, 1, 1 },
                       new double[] { 98.680, 47.345 });
}
 
Example #14
Source File: IterativeLegendreGaussIntegrator.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Compute the n-th stage integral.
 *
 * @param n Number of steps.
 * @return the value of n-th stage integral.
 * @throws TooManyEvaluationsException if the maximum number of evaluations
 * is exceeded.
 */
private double stage(final int n)
    throws TooManyEvaluationsException {
    // Function to be integrated is stored in the base class.
    final UnivariateFunction f = new UnivariateFunction() {
            public double value(double x) {
                return computeObjectiveValue(x);
            }
        };

    final double min = getMin();
    final double max = getMax();
    final double step = (max - min) / n;

    double sum = 0;
    for (int i = 0; i < n; i++) {
        // Integrate over each sub-interval [a, b].
        final double a = min + i * step;
        final double b = a + step;
        final GaussIntegrator g = FACTORY.legendreHighPrecision(numberOfPoints, a, b);
        sum += g.integrate(f);
    }

    return sum;
}
 
Example #15
Source File: BrentOptimizerTest.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void testSinMin() {
    UnivariateFunction f = new Sin();
    UnivariateOptimizer optimizer = new BrentOptimizer(1e-10, 1e-14);
    Assert.assertEquals(3 * Math.PI / 2, optimizer.optimize(200, f, GoalType.MINIMIZE, 4, 5).getPoint(), 1e-8);
    Assert.assertTrue(optimizer.getEvaluations() <= 50);
    Assert.assertEquals(200, optimizer.getMaxEvaluations());
    Assert.assertEquals(3 * Math.PI / 2, optimizer.optimize(200, f, GoalType.MINIMIZE, 1, 5).getPoint(), 1e-8);
    Assert.assertTrue(optimizer.getEvaluations() <= 100);
    Assert.assertTrue(optimizer.getEvaluations() >= 15);
    try {
        optimizer.optimize(10, f, GoalType.MINIMIZE, 4, 5);
        Assert.fail("an exception should have been thrown");
    } catch (TooManyEvaluationsException fee) {
        // expected
    }
}
 
Example #16
Source File: MinpackTest.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
private void minpackTest(MinpackFunction function, boolean exceptionExpected) {
      LevenbergMarquardtOptimizer optimizer
          = new LevenbergMarquardtOptimizer(FastMath.sqrt(2.22044604926e-16),
                                            FastMath.sqrt(2.22044604926e-16),
                                            2.22044604926e-16);
//      Assert.assertTrue(function.checkTheoreticalStartCost(optimizer.getRMS()));
      try {
          PointVectorValuePair optimum =
              optimizer.optimize(400 * (function.getN() + 1), function,
                                 function.getTarget(), function.getWeight(),
                                 function.getStartPoint());
          Assert.assertFalse(exceptionExpected);
          function.checkTheoreticalMinCost(optimizer.getRMS());
          function.checkTheoreticalMinParams(optimum);
      } catch (TooManyEvaluationsException e) {
          Assert.assertTrue(exceptionExpected);
      }
  }
 
Example #17
Source File: MullerSolver.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
protected double doSolve()
    throws TooManyEvaluationsException,
           NumberIsTooLargeException,
           NoBracketingException {
    final double min = getMin();
    final double max = getMax();
    final double initial = getStartValue();

    final double functionValueAccuracy = getFunctionValueAccuracy();

    verifySequence(min, initial, max);

    // check for zeros before verifying bracketing
    final double fMin = computeObjectiveValue(min);
    if (FastMath.abs(fMin) < functionValueAccuracy) {
        return min;
    }
    final double fMax = computeObjectiveValue(max);
    if (FastMath.abs(fMax) < functionValueAccuracy) {
        return max;
    }
    final double fInitial = computeObjectiveValue(initial);
    if (FastMath.abs(fInitial) <  functionValueAccuracy) {
        return initial;
    }

    verifyBracketing(min, max);

    if (isBracketing(min, initial)) {
        return solve(min, initial, fMin, fInitial);
    } else {
        return solve(initial, max, fInitial, fMax);
    }
}
 
Example #18
Source File: BracketingNthOrderBrentSolver.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/** {@inheritDoc} */
public double solve(int maxEval, UnivariateFunction f, double min,
                    double max, double startValue,
                    AllowedSolution allowedSolution)
    throws TooManyEvaluationsException,
           NumberIsTooLargeException,
           NoBracketingException {
    this.allowed = allowedSolution;
    return super.solve(maxEval, f, min, max, startValue);
}
 
Example #19
Source File: BaseAbstractUnivariateSolver.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Increment the evaluation count by one.
 * Method {@link #computeObjectiveValue(double)} calls this method internally.
 * It is provided for subclasses that do not exclusively use
 * {@code computeObjectiveValue} to solve the function.
 * See e.g. {@link AbstractDifferentiableUnivariateSolver}.
 */
protected void incrementEvaluationCount() {
    try {
        evaluations.incrementCount();
    } catch (MaxCountExceededException e) {
        throw new TooManyEvaluationsException(e.getMax());
    }
}
 
Example #20
Source File: BaseAbstractMultivariateVectorOptimizer.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Compute the objective function value.
 *
 * @param point Point at which the objective function must be evaluated.
 * @return the objective function value at the specified point.
 * @throws TooManyEvaluationsException if the maximal number of evaluations is
 * exceeded.
 */
protected double[] computeObjectiveValue(double[] point) {
    try {
        evaluations.incrementCount();
    } catch (MaxCountExceededException e) {
        throw new TooManyEvaluationsException(e.getMax());
    }
    return function.value(point);
}
 
Example #21
Source File: SimpsonIntegrator.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override
protected double doIntegrate()
    throws TooManyEvaluationsException, MaxCountExceededException {

    TrapezoidIntegrator qtrap = new TrapezoidIntegrator();
    if (getMinimalIterationCount() == 1) {
        return (4 * qtrap.stage(this, 1) - qtrap.stage(this, 0)) / 3.0;
    }

    // Simpson's rule requires at least two trapezoid stages.
    double olds = 0;
    double oldt = qtrap.stage(this, 0);
    while (true) {
        final double t = qtrap.stage(this, iterations.getCount());
        iterations.incrementCount();
        final double s = (4 * t - oldt) / 3.0;
        if (iterations.getCount() >= getMinimalIterationCount()) {
            final double delta = FastMath.abs(s - olds);
            final double rLimit =
                getRelativeAccuracy() * (FastMath.abs(olds) + FastMath.abs(s)) * 0.5;
            if ((delta <= rLimit) || (delta <= getAbsoluteAccuracy())) {
                return s;
            }
        }
        olds = s;
        oldt = t;
    }

}
 
Example #22
Source File: BracketingNthOrderBrentSolver.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/** {@inheritDoc} */
public double solve(int maxEval, UnivariateFunction f, double min,
                    double max, double startValue,
                    AllowedSolution allowedSolution)
    throws TooManyEvaluationsException,
           NumberIsTooLargeException,
           NoBracketingException {
    this.allowed = allowedSolution;
    return super.solve(maxEval, f, min, max, startValue);
}
 
Example #23
Source File: LegendreGaussIntegrator.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override
protected double doIntegrate()
    throws MathIllegalArgumentException, TooManyEvaluationsException, MaxCountExceededException {

    // compute first estimate with a single step
    double oldt = stage(1);

    int n = 2;
    while (true) {

        // improve integral with a larger number of steps
        final double t = stage(n);

        // estimate error
        final double delta = FastMath.abs(t - oldt);
        final double limit =
            FastMath.max(getAbsoluteAccuracy(),
                         getRelativeAccuracy() * (FastMath.abs(oldt) + FastMath.abs(t)) * 0.5);

        // check convergence
        if ((iterations.getCount() + 1 >= getMinimalIterationCount()) && (delta <= limit)) {
            return t;
        }

        // prepare next iteration
        double ratio = FastMath.min(4, FastMath.pow(delta / limit, 0.5 / abscissas.length));
        n = FastMath.max((int) (ratio * n), n + 1);
        oldt = t;
        iterations.incrementCount();

    }

}
 
Example #24
Source File: BracketingNthOrderBrentSolver.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/** {@inheritDoc} */
public double solve(int maxEval, UnivariateFunction f, double min,
                    double max, AllowedSolution allowedSolution)
    throws TooManyEvaluationsException,
           NumberIsTooLargeException,
           NoBracketingException {
    this.allowed = allowedSolution;
    return super.solve(maxEval, f, min, max);
}
 
Example #25
Source File: BaseAbstractUnivariateIntegrator.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/** {@inheritDoc} */
public double integrate(final int maxEval, final UnivariateFunction f,
                        final double lower, final double upper)
    throws TooManyEvaluationsException, MaxCountExceededException,
           MathIllegalArgumentException, NullArgumentException {

    // Initialization.
    setup(maxEval, f, lower, upper);

    // Perform computation.
    return doIntegrate();

}
 
Example #26
Source File: SimplexOptimizerNelderMeadTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@Test(expected = TooManyEvaluationsException.class)
public void testMaxIterations() {
    Powell powell = new Powell();
    SimplexOptimizer optimizer = new SimplexOptimizer(-1, 1e-3);
    optimizer.setSimplex(new NelderMeadSimplex(4));
    optimizer.optimize(20, powell, GoalType.MINIMIZE, new double[] { 3, -1, 0, 1 });
}
 
Example #27
Source File: BrentOptimizerTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void testQuinticMax() {
    // The quintic function has zeros at 0, +-0.5 and +-1.
    // The function has a local maximum at 0.27195613.
    UnivariateFunction f = new QuinticFunction();
    UnivariateOptimizer optimizer = new BrentOptimizer(1e-12, 1e-14);
    Assert.assertEquals(0.27195613, optimizer.optimize(100, f, GoalType.MAXIMIZE, 0.2, 0.3).getPoint(), 1e-8);
    try {
        optimizer.optimize(5, f, GoalType.MAXIMIZE, 0.2, 0.3);
        Assert.fail("an exception should have been thrown");
    } catch (TooManyEvaluationsException miee) {
        // expected
    }
}
 
Example #28
Source File: SimpsonIntegrator.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override
protected double doIntegrate()
    throws TooManyEvaluationsException, MaxCountExceededException {

    TrapezoidIntegrator qtrap = new TrapezoidIntegrator();
    if (getMinimalIterationCount() == 1) {
        return (4 * qtrap.stage(this, 1) - qtrap.stage(this, 0)) / 3.0;
    }

    // Simpson's rule requires at least two trapezoid stages.
    double olds = 0;
    double oldt = qtrap.stage(this, 0);
    while (true) {
        final double t = qtrap.stage(this, iterations.getCount());
        iterations.incrementCount();
        final double s = (4 * t - oldt) / 3.0;
        if (iterations.getCount() >= getMinimalIterationCount()) {
            final double delta = FastMath.abs(s - olds);
            final double rLimit =
                getRelativeAccuracy() * (FastMath.abs(olds) + FastMath.abs(s)) * 0.5;
            if ((delta <= rLimit) || (delta <= getAbsoluteAccuracy())) {
                return s;
            }
        }
        olds = s;
        oldt = t;
    }

}
 
Example #29
Source File: BracketingNthOrderBrentSolver.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/** {@inheritDoc} */
public double solve(int maxEval, UnivariateFunction f, double min,
                    double max, AllowedSolution allowedSolution)
    throws TooManyEvaluationsException,
           NumberIsTooLargeException,
           NoBracketingException {
    this.allowed = allowedSolution;
    return super.solve(maxEval, f, min, max);
}
 
Example #30
Source File: BisectionSolver.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
protected double doSolve()
    throws TooManyEvaluationsException {
    double min = getMin();
    double max = getMax();
    verifyInterval(min, max);
    final double absoluteAccuracy = getAbsoluteAccuracy();
    double m;
    double fm;
    double fmin;

    while (true) {
        m = UnivariateSolverUtils.midpoint(min, max);
        fmin = computeObjectiveValue(min);
        fm = computeObjectiveValue(m);

        if (fm * fmin > 0) {
            // max and m bracket the root.
            min = m;
        } else {
            // min and m bracket the root.
            max = m;
        }

        if (FastMath.abs(max - min) <= absoluteAccuracy) {
            m = UnivariateSolverUtils.midpoint(min, max);
            return m;
        }
    }
}