org.apache.commons.math.FunctionEvaluationException Java Examples

The following examples show how to use org.apache.commons.math.FunctionEvaluationException. 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: CurveFitter.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/** Fit a curve.
 * <p>This method compute the coefficients of the curve that best
 * fit the sample of observed points previously given through calls
 * to the {@link #addObservedPoint(WeightedObservedPoint)
 * addObservedPoint} method.</p>
 * @param f parametric function to fit
 * @param initialGuess first guess of the function parameters
 * @return fitted parameters
 * @exception FunctionEvaluationException if the objective function throws one during
 * the search
 * @exception OptimizationException if the algorithm failed to converge
 * @exception IllegalArgumentException if the start point dimension is wrong
 */
public double[] fit(final ParametricRealFunction f,
                    final double[] initialGuess)
    throws FunctionEvaluationException, OptimizationException, IllegalArgumentException {

    // prepare least squares problem
    double[] target  = new double[observations.size()];
    double[] weights = new double[observations.size()];
    int i = 0;
    for (WeightedObservedPoint point : observations) {
        target[i]  = point.getY();
        weights[i] = point.getWeight();
        ++i;
    }

    // perform the fit
    VectorialPointValuePair optimum =
        optimizer.optimize(new TheoreticalValuesFunction(f), target, weights, initialGuess);

    // extract the coefficients
    return optimum.getPointRef();

}
 
Example #2
Source File: MultiDirectionalTest.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void testMath283()
    throws FunctionEvaluationException, OptimizationException {
    // fails because MultiDirectional.iterateSimplex is looping forever
    // the while(true) should be replaced with a convergence check
    MultiDirectional multiDirectional = new MultiDirectional();
    multiDirectional.setMaxIterations(100);
    multiDirectional.setMaxEvaluations(1000);

    final Gaussian2D function = new Gaussian2D(0.0, 0.0, 1.0);

    RealPointValuePair estimate = multiDirectional.optimize(function,
                                  GoalType.MAXIMIZE, function.getMaximumPosition());

    final double EPSILON = 1e-5;

    final double expectedMaximum = function.getMaximum();
    final double actualMaximum = estimate.getValue();
    Assert.assertEquals(expectedMaximum, actualMaximum, EPSILON);

    final double[] expectedPosition = function.getMaximumPosition();
    final double[] actualPosition = estimate.getPoint();
    Assert.assertEquals(expectedPosition[0], actualPosition[0], EPSILON );
    Assert.assertEquals(expectedPosition[1], actualPosition[1], EPSILON );

}
 
Example #3
Source File: LegendreGaussIntegratorTest.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
public void testExactIntegration()
    throws ConvergenceException, FunctionEvaluationException {
    Random random = new Random(86343623467878363l);
    for (int n = 2; n < 6; ++n) {
        LegendreGaussIntegrator integrator =
            new LegendreGaussIntegrator(n, 64);

        // an n points Gauss-Legendre integrator integrates 2n-1 degree polynoms exactly
        for (int degree = 0; degree <= 2 * n - 1; ++degree) {
            for (int i = 0; i < 10; ++i) {
                double[] coeff = new double[degree + 1];
                for (int k = 0; k < coeff.length; ++k) {
                    coeff[k] = 2 * random.nextDouble() - 1;
                }
                PolynomialFunction p = new PolynomialFunction(coeff);
                double result    = integrator.integrate(p, -5.0, 15.0);
                double reference = exactIntegration(p, -5.0, 15.0);
                assertEquals(n + " " + degree + " " + i, reference, result, 1.0e-12 * (1.0 + Math.abs(reference)));
            }
        }

    }
}
 
Example #4
Source File: LaguerreSolver.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Find a real root in the given interval with initial value.
 * <p>
 * Requires bracketing condition.</p>
 *
 * @param f function to solve (must be polynomial)
 * @param min the lower bound for the interval
 * @param max the upper bound for the interval
 * @param initial the start value to use
 * @return the point at which the function value is zero
 * @throws ConvergenceException if the maximum iteration count is exceeded
 * or the solver detects convergence problems otherwise
 * @throws FunctionEvaluationException if an error occurs evaluating the
 * function
 * @throws IllegalArgumentException if any parameters are invalid
 */
public double solve(final UnivariateRealFunction f,
                    final double min, final double max, final double initial)
    throws ConvergenceException, FunctionEvaluationException {

    // check for zeros before verifying bracketing
    if (f.value(min) == 0.0) {
        return min;
    }
    if (f.value(max) == 0.0) {
        return max;
    }
    if (f.value(initial) == 0.0) {
        return initial;
    }

    verifyBracketing(min, max, f);
    verifySequence(min, initial, max);
    if (isBracketing(min, initial, f)) {
        return solve(f, min, initial);
    } else {
        return solve(f, initial, max);
    }

}
 
Example #5
Source File: NonLinearConjugateGradientOptimizerTest.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
public void testColumnsPermutation() throws FunctionEvaluationException, OptimizationException {

        LinearProblem problem =
            new LinearProblem(new double[][] { { 1.0, -1.0 }, { 0.0, 2.0 }, { 1.0, -2.0 } },
                              new double[] { 4.0, 6.0, 1.0 });

        NonLinearConjugateGradientOptimizer optimizer =
            new NonLinearConjugateGradientOptimizer(ConjugateGradientFormula.POLAK_RIBIERE);
        optimizer.setMaxIterations(100);
        optimizer.setConvergenceChecker(new SimpleScalarValueChecker(1.0e-6, 1.0e-6));
        RealPointValuePair optimum =
            optimizer.optimize(problem, GoalType.MINIMIZE, new double[] { 0, 0 });
        assertEquals(7.0, optimum.getPoint()[0], 1.0e-10);
        assertEquals(3.0, optimum.getPoint()[1], 1.0e-10);
        assertEquals(0.0, optimum.getValue(), 1.0e-10);

    }
 
Example #6
Source File: AbstractLeastSquaresOptimizer.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Guess the errors in optimized parameters.
 * <p>Guessing is covariance-based, it only gives rough order of magnitude.</p>
 * @return errors in optimized parameters
 * @exception FunctionEvaluationException if the function jacobian cannot b evaluated
 * @exception OptimizationException if the covariances matrix cannot be computed
 * or the number of degrees of freedom is not positive (number of measurements
 * lesser or equal to number of parameters)
 */
public double[] guessParametersErrors()
    throws FunctionEvaluationException, OptimizationException {
    if (rows <= cols) {
        throw new OptimizationException(
                "no degrees of freedom ({0} measurements, {1} parameters)",
                rows, cols);
    }
    double[] errors = new double[cols];
    final double c = Math.sqrt(getChiSquare() / (rows - cols));
    double[][] covar = getCovariances();
    for (int i = 0; i < errors.length; ++i) {
        errors[i] = Math.sqrt(covar[i][i]) * c;
    }
    return errors;
}
 
Example #7
Source File: MultiDirectionalTest.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void testMath283()
    throws FunctionEvaluationException, OptimizationException {
    // fails because MultiDirectional.iterateSimplex is looping forever
    // the while(true) should be replaced with a convergence check
    MultiDirectional multiDirectional = new MultiDirectional();
    multiDirectional.setMaxIterations(100);
    multiDirectional.setMaxEvaluations(1000);

    final Gaussian2D function = new Gaussian2D(0.0, 0.0, 1.0);

    RealPointValuePair estimate = multiDirectional.optimize(function,
                                  GoalType.MAXIMIZE, function.getMaximumPosition());

    final double EPSILON = 1e-5;

    final double expectedMaximum = function.getMaximum();
    final double actualMaximum = estimate.getValue();
    Assert.assertEquals(expectedMaximum, actualMaximum, EPSILON);

    final double[] expectedPosition = function.getMaximumPosition();
    final double[] actualPosition = estimate.getPoint();
    Assert.assertEquals(expectedPosition[0], actualPosition[0], EPSILON );
    Assert.assertEquals(expectedPosition[1], actualPosition[1], EPSILON );

}
 
Example #8
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 f the integrand function
 * @param min the lower bound for the interval
 * @param max the upper bound for the interval
 * @param n number of steps
 * @return the value of n-th stage integral
 * @throws FunctionEvaluationException if an error occurs evaluating the
 * function
 */
private double stage(final UnivariateRealFunction f,
                     final double min, final double max, final int n)
    throws FunctionEvaluationException {

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

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

    return halfStep * sum;

}
 
Example #9
Source File: LevenbergMarquardtOptimizerTest.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
public void testTwoSets() throws FunctionEvaluationException, OptimizationException {
    double epsilon = 1.0e-7;
    LinearProblem problem = new LinearProblem(new double[][] {
            {  2,  1,   0,  4,       0, 0 },
            { -4, -2,   3, -7,       0, 0 },
            {  4,  1,  -2,  8,       0, 0 },
            {  0, -3, -12, -1,       0, 0 },
            {  0,  0,   0,  0, epsilon, 1 },
            {  0,  0,   0,  0,       1, 1 }
    }, new double[] { 2, -9, 2, 2, 1 + epsilon * epsilon, 2});

    LevenbergMarquardtOptimizer optimizer = new LevenbergMarquardtOptimizer();
    VectorialPointValuePair optimum =
        optimizer.optimize(problem, problem.target, new double[] { 1, 1, 1, 1, 1, 1 },
                           new double[] { 0, 0, 0, 0, 0, 0 });
    assertEquals(0, optimizer.getRMS(), 1.0e-10);
    assertEquals( 3.0, optimum.getPoint()[0], 1.0e-10);
    assertEquals( 4.0, optimum.getPoint()[1], 1.0e-10);
    assertEquals(-1.0, optimum.getPoint()[2], 1.0e-10);
    assertEquals(-2.0, optimum.getPoint()[3], 1.0e-10);
    assertEquals( 1.0 + epsilon, optimum.getPoint()[4], 1.0e-10);
    assertEquals( 1.0 - epsilon, optimum.getPoint()[5], 1.0e-10);

}
 
Example #10
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 f the integrand function
 * @param min the lower bound for the interval
 * @param max the upper bound for the interval
 * @param n number of steps
 * @return the value of n-th stage integral
 * @throws FunctionEvaluationException if an error occurs evaluating the
 * function
 */
private double stage(final UnivariateRealFunction f,
                     final double min, final double max, final int n)
    throws FunctionEvaluationException {

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

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

    return halfStep * sum;

}
 
Example #11
Source File: NonLinearConjugateGradientOptimizerTest.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
public void testRedundantEquations() throws FunctionEvaluationException, OptimizationException {
    LinearProblem problem = new LinearProblem(new double[][] {
            { 1.0,  1.0 },
            { 1.0, -1.0 },
            { 1.0,  3.0 }
    }, new double[] { 3.0, 1.0, 5.0 });

    NonLinearConjugateGradientOptimizer optimizer =
        new NonLinearConjugateGradientOptimizer(ConjugateGradientFormula.POLAK_RIBIERE);
    optimizer.setMaxIterations(100);
    optimizer.setConvergenceChecker(new SimpleScalarValueChecker(1.0e-6, 1.0e-6));
    RealPointValuePair optimum =
        optimizer.optimize(problem, GoalType.MINIMIZE, new double[] { 1, 1 });
    assertEquals(2.0, optimum.getPoint()[0], 1.0e-8);
    assertEquals(1.0, optimum.getPoint()[1], 1.0e-8);

}
 
Example #12
Source File: AbstractScalarDifferentiableOptimizer.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/** {@inheritDoc} */
public RealPointValuePair optimize(final DifferentiableMultivariateRealFunction f,
                                     final GoalType goalType,
                                     final double[] startPoint)
    throws FunctionEvaluationException, OptimizationException, IllegalArgumentException {

    // reset counters
    iterations          = 0;
    evaluations         = 0;
    gradientEvaluations = 0;

    // store optimization problem characteristics
    function = f;
    gradient = f.gradient();
    goal     = goalType;
    point    = startPoint.clone();

    return doOptimize();

}
 
Example #13
Source File: MultiDirectionalTest.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void testMath283()
    throws FunctionEvaluationException, OptimizationException {
    // fails because MultiDirectional.iterateSimplex is looping forever
    // the while(true) should be replaced with a convergence check
    MultiDirectional multiDirectional = new MultiDirectional();
    multiDirectional.setMaxIterations(100);
    multiDirectional.setMaxEvaluations(1000);

    final Gaussian2D function = new Gaussian2D(0.0, 0.0, 1.0);

    RealPointValuePair estimate = multiDirectional.optimize(function,
                                  GoalType.MAXIMIZE, function.getMaximumPosition());

    final double EPSILON = 1e-5;

    final double expectedMaximum = function.getMaximum();
    final double actualMaximum = estimate.getValue();
    Assert.assertEquals(expectedMaximum, actualMaximum, EPSILON);

    final double[] expectedPosition = function.getMaximumPosition();
    final double[] actualPosition = estimate.getPoint();
    Assert.assertEquals(expectedPosition[0], actualPosition[0], EPSILON );
    Assert.assertEquals(expectedPosition[1], actualPosition[1], EPSILON );

}
 
Example #14
Source File: RiddersSolver.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Find a root in the given interval with initial value.
 * <p>
 * Requires bracketing condition.</p>
 *
 * @param f the function to solve
 * @param min the lower bound for the interval
 * @param max the upper bound for the interval
 * @param initial the start value to use
 * @return the point at which the function value is zero
 * @throws MaxIterationsExceededException if the maximum iteration count is exceeded
 * @throws FunctionEvaluationException if an error occurs evaluating the
 * function
 * @throws IllegalArgumentException if any parameters are invalid
 */
public double solve(final UnivariateRealFunction f,
                    final double min, final double max, final double initial)
    throws MaxIterationsExceededException, FunctionEvaluationException {

    // check for zeros before verifying bracketing
    if (f.value(min) == 0.0) { return min; }
    if (f.value(max) == 0.0) { return max; }
    if (f.value(initial) == 0.0) { return initial; }

    verifyBracketing(min, max, f);
    verifySequence(min, initial, max);
    if (isBracketing(min, initial, f)) {
        return solve(f, min, initial);
    } else {
        return solve(f, initial, max);
    }
}
 
Example #15
Source File: LevenbergMarquardtOptimizerTest.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
public void testMath199() throws FunctionEvaluationException {
    try {
        QuadraticProblem problem = new QuadraticProblem();
        problem.addPoint (0, -3.182591015485607);
        problem.addPoint (1, -2.5581184967730577);
        problem.addPoint (2, -2.1488478161387325);
        problem.addPoint (3, -1.9122489313410047);
        problem.addPoint (4, 1.7785661310051026);
        LevenbergMarquardtOptimizer optimizer = new LevenbergMarquardtOptimizer();
        optimizer.setQRRankingThreshold(0);
        optimizer.optimize(problem,
                           new double[] { 0, 0, 0, 0, 0 },
                           new double[] { 0.0, 4.4e-323, 1.0, 4.4e-323, 0.0 },
                           new double[] { 0, 0, 0 });
        fail("an exception should have been thrown");
    } catch (ConvergenceException ee) {
        // expected behavior
    }

}
 
Example #16
Source File: GaussNewtonOptimizerTest.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
public void testRedundantEquations() throws FunctionEvaluationException, OptimizationException {
    LinearProblem problem = new LinearProblem(new double[][] {
            { 1.0,  1.0 },
            { 1.0, -1.0 },
            { 1.0,  3.0 }
    }, new double[] { 3.0, 1.0, 5.0 });

    GaussNewtonOptimizer optimizer = new GaussNewtonOptimizer(true);
    optimizer.setMaxIterations(100);
    optimizer.setConvergenceChecker(new SimpleVectorialValueChecker(1.0e-6, 1.0e-6));
    VectorialPointValuePair optimum =
        optimizer.optimize(problem, problem.target, new double[] { 1, 1, 1 },
                           new double[] { 1, 1 });
    assertEquals(0, optimizer.getRMS(), 1.0e-10);
    assertEquals(2.0, optimum.getPoint()[0], 1.0e-8);
    assertEquals(1.0, optimum.getPoint()[1], 1.0e-8);

}
 
Example #17
Source File: GaussianFitterTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Poor data: right of peak is missing.
 *
 * @throws OptimizationException in the event of a test case error
 * @throws FunctionEvaluationException in the event of a test case error
 */
@Test
public void testFit06()
throws OptimizationException, FunctionEvaluationException {
    GaussianFitter fitter = new GaussianFitter(new LevenbergMarquardtOptimizer());
    addDatasetToGaussianFitter(DATASET4, fitter);
    GaussianFunction fitFunction = fitter.fit();
    assertEquals(530.3649792355617, fitFunction.getA(), 1e-4);
    assertEquals(284517.0835567514, fitFunction.getB(), 1e-4);
    assertEquals(-13.5355534565105, fitFunction.getC(), 1e-4);
    assertEquals(1.512353018625465, fitFunction.getD(), 1e-4);
}
 
Example #18
Source File: ComposableFunction.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/** Precompose the instance with another function.
 * <p>
 * The composed function h created by {@code h = g.of(f)} is such
 * that {@code h.value(x) == g.value(f.value(x))} for all x.
 * </p>
 * @param f function to compose with
 * @return a new function which computes {@code this.value(f.value(x))}
 * @see #postCompose(UnivariateRealFunction)
 */
public ComposableFunction of(final UnivariateRealFunction f) {
    return new ComposableFunction() {
        @Override
        /** {@inheritDoc} */
        public double value(double x) throws FunctionEvaluationException {
            return ComposableFunction.this.value(f.value(x));
        }
    };
}
 
Example #19
Source File: ComposableFunction.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Return a function adding the instance and another function.
 * @param f function to combine with the instance
 * @return a new function which computes {@code this.value(x) + f.value(x)}
 */
public ComposableFunction add(final UnivariateRealFunction f) {
    return new ComposableFunction() {
        @Override
        /** {@inheritDoc} */
        public double value(double x) throws FunctionEvaluationException {
            return ComposableFunction.this.value(x) + f.value(x);
        }
    };
}
 
Example #20
Source File: LegendreGaussIntegrator.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/** {@inheritDoc} */
public double integrate(final UnivariateRealFunction f,
        final double min, final double max)
    throws ConvergenceException,  FunctionEvaluationException, IllegalArgumentException {
    
    clearResult();
    verifyInterval(min, max);
    verifyIterationCount();

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

    int n = 2;
    for (int i = 0; i < maximalIterationCount; ++i) {

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

        // estimate error
        final double delta = Math.abs(t - oldt);
        final double limit =
            Math.max(absoluteAccuracy,
                     relativeAccuracy * (Math.abs(oldt) + Math.abs(t)) * 0.5);

        // check convergence
        if ((i + 1 >= minimalIterationCount) && (delta <= limit)) {
            setResult(t, i);
            return result;
        }

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

    }

    throw new MaxIterationsExceededException(maximalIterationCount);

}
 
Example #21
Source File: GaussianFitterTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Zero points is not enough observed points.
 *
 * @throws OptimizationException in the event of a test case error
 * @throws FunctionEvaluationException in the event of a test case error
 */
@Test(expected=IllegalArgumentException.class)
public void testFit02()
throws OptimizationException, FunctionEvaluationException {
    GaussianFitter fitter = new GaussianFitter(new LevenbergMarquardtOptimizer());
    fitter.fit();
}
 
Example #22
Source File: GaussNewtonOptimizerTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
public void testTrivial() throws FunctionEvaluationException, OptimizationException {
    LinearProblem problem =
        new LinearProblem(new double[][] { { 2 } }, new double[] { 3 });
    GaussNewtonOptimizer optimizer = new GaussNewtonOptimizer(true);
    optimizer.setMaxIterations(100);
    optimizer.setConvergenceChecker(new SimpleVectorialValueChecker(1.0e-6, 1.0e-6));
    VectorialPointValuePair optimum =
        optimizer.optimize(problem, problem.target, new double[] { 1 }, new double[] { 0 });
    assertEquals(0, optimizer.getRMS(), 1.0e-10);
    assertEquals(1.5, optimum.getPoint()[0], 1.0e-10);
    assertEquals(3.0, optimum.getValue()[0], 1.0e-10);
}
 
Example #23
Source File: LevenbergMarquardtOptimizerTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
public void testInconsistentEquations() throws FunctionEvaluationException, OptimizationException {
    LinearProblem problem = new LinearProblem(new double[][] {
            { 1.0,  1.0 },
            { 1.0, -1.0 },
            { 1.0,  3.0 }
    }, new double[] { 3.0, 1.0, 4.0 });

    LevenbergMarquardtOptimizer optimizer = new LevenbergMarquardtOptimizer();
    optimizer.optimize(problem, problem.target, new double[] { 1, 1, 1 }, new double[] { 1, 1 });
    assertTrue(optimizer.getRMS() > 0.1);

}
 
Example #24
Source File: JGenProg2017_00139_t.java    From coming with MIT License 5 votes vote down vote up
/**
  * This method attempts to find two values a and b satisfying <ul>
  * <li> <code> lowerBound <= a < initial < b <= upperBound</code> </li>
  * <li> <code> f(a) * f(b) <= 0 </code> </li>
  * </ul>
  * If f is continuous on <code>[a,b],</code> this means that <code>a</code>
  * and <code>b</code> bracket a root of f.
  * <p>
  * The algorithm starts by setting 
  * <code>a := initial -1; b := initial +1,</code> examines the value of the
  * function at <code>a</code> and <code>b</code> and keeps moving
  * the endpoints out by one unit each time through a loop that terminates 
  * when one of the following happens: <ul>
  * <li> <code> f(a) * f(b) <= 0 </code> --  success!</li>
  * <li> <code> a = lower </code> and <code> b = upper</code> 
  * -- ConvergenceException </li>
  * <li> <code> maximumIterations</code> iterations elapse 
  * -- ConvergenceException </li></ul></p>
  * 
  * @param function the function
  * @param initial initial midpoint of interval being expanded to
  * bracket a root
  * @param lowerBound lower bound (a is never lower than this value)
  * @param upperBound upper bound (b never is greater than this
  * value)
  * @param maximumIterations maximum number of iterations to perform
  * @return a two element array holding {a, b}.
  * @throws ConvergenceException if the algorithm fails to find a and b
  * satisfying the desired conditions
  * @throws FunctionEvaluationException if an error occurs evaluating the 
  * function
  * @throws IllegalArgumentException if function is null, maximumIterations
  * is not positive, or initial is not between lowerBound and upperBound
  */
 public static double[] bracket(UnivariateRealFunction function,
         double initial, double lowerBound, double upperBound, 
         int maximumIterations) throws ConvergenceException, 
         FunctionEvaluationException {
     
     if (function == null) {
         throw MathRuntimeException.createIllegalArgumentException("function is null");
     }
     if (maximumIterations <= 0)  {
         throw MathRuntimeException.createIllegalArgumentException(
               "bad value for maximum iterations number: {0}", maximumIterations);
     }
     if (initial < lowerBound || initial > upperBound || lowerBound >= upperBound) {
         throw MathRuntimeException.createIllegalArgumentException(
               "invalid bracketing parameters:  lower bound={0},  initial={1}, upper bound={2}",
               lowerBound, initial, upperBound);
     }
     double a = initial;
     double b = initial;
     double fa;
     double fb;
     int numIterations = 0 ;
 
     do {
         a = Math.max(a - 1.0, lowerBound);
         b = Math.min(b + 1.0, upperBound);
         fa = function.value(a);
         
         fb = function.value(b);
         numIterations++ ;
     } while ((fa * fb > 0.0) && (numIterations < maximumIterations) && 
             ((a > lowerBound) || (b < upperBound)));

    if (function == null) {
throw org.apache.commons.math.MathRuntimeException.createIllegalArgumentException("function is null");
}
     
     return new double[]{a, b};
 }
 
Example #25
Source File: AbstractRealVector.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/** {@inheritDoc} */
public RealVector mapSignumToSelf() {
    try {
        return mapToSelf(ComposableFunction.SIGNUM);
    } catch (FunctionEvaluationException e) {
        throw new IllegalArgumentException(e);
    }
}
 
Example #26
Source File: AbstractRealVector.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/** {@inheritDoc} */
public RealVector mapSinToSelf() {
    try {
        return mapToSelf(ComposableFunction.SIN);
    } catch (FunctionEvaluationException e) {
        throw new IllegalArgumentException(e);
    }
}
 
Example #27
Source File: BinaryFunction.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/** Get a composable function by fixing the second argument of the instance.
 * @param fixedY fixed value of the second argument
 * @return a function such that {@code f.value(x) == value(x, fixedY)}
 */
public ComposableFunction fix2ndArgument(final double fixedY) {
    return new ComposableFunction() {
        @Override
        /** {@inheritDoc} */
        public double value(double x) throws FunctionEvaluationException {
            return BinaryFunction.this.value(x, fixedY);
        }
    };
}
 
Example #28
Source File: ComposableFunction.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Return a function subtracting another function from the instance.
 * @param f function to combine with the instance
 * @return a new function which computes {@code this.value(x) - f.value(x)}
 */
public ComposableFunction subtract(final UnivariateRealFunction f) {
    return new ComposableFunction() {
        @Override
        /** {@inheritDoc} */
        public double value(double x) throws FunctionEvaluationException {
            return ComposableFunction.this.value(x) - f.value(x);
        }
    };
}
 
Example #29
Source File: ComposableFunction.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Return a function adding a constant term to the instance.
 * @param a term to add
 * @return a new function which computes {@code this.value(x) + a}
 */
public ComposableFunction add(final double a) {
    return new ComposableFunction() {
        @Override
        /** {@inheritDoc} */
        public double value(double x) throws FunctionEvaluationException {
            return ComposableFunction.this.value(x) + a;
        }
    };
}
 
Example #30
Source File: NewtonSolver.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Find a zero near the value <code>startValue</code>.
 *
 * @param f the function to solve
 * @param min the lower bound for the interval (ignored).
 * @param max the upper bound for the interval (ignored).
 * @param startValue the start value to use.
 * @return the value where the function is zero
 * @throws MaxIterationsExceededException if the maximum iteration count is exceeded
 * @throws FunctionEvaluationException if an error occurs evaluating the
 * function or derivative
 * @throws IllegalArgumentException if startValue is not between min and max or
 * if function is not a {@link DifferentiableUnivariateRealFunction} instance
 */
public double solve(final UnivariateRealFunction f,
                    final double min, final double max, final double startValue)
    throws MaxIterationsExceededException, FunctionEvaluationException {

    try {

        final UnivariateRealFunction derivative =
            ((DifferentiableUnivariateRealFunction) f).derivative();
        clearResult();
        verifySequence(min, startValue, max);

        double x0 = startValue;
        double x1;

        int i = 0;
        while (i < maximalIterationCount) {

            x1 = x0 - (f.value(x0) / derivative.value(x0));
            if (Math.abs(x1 - x0) <= absoluteAccuracy) {
                setResult(x1, i);
                return x1;
            }

            x0 = x1;
            ++i;
        }

        throw new MaxIterationsExceededException(maximalIterationCount);
    } catch (ClassCastException cce) {
        throw MathRuntimeException.createIllegalArgumentException("function is not differentiable");
    }
}