Example usage for org.apache.commons.math.analysis.solvers BrentSolver solve

List of usage examples for org.apache.commons.math.analysis.solvers BrentSolver solve

Introduction

In this page you can find the example usage for org.apache.commons.math.analysis.solvers BrentSolver solve.

Prototype

@Override
public double solve(int maxEval, final UnivariateRealFunction f, final double min, final double max)
        throws MaxIterationsExceededException, FunctionEvaluationException 

Source Link

Document

Find a zero in the given interval.

Usage

From source file:com.opengamma.analytics.math.interpolation.LogLinearWithSeasonalitiesInterpolator1D.java

@Override
public Double interpolate(final Interpolator1DDataBundle model, final Double value) {
    Validate.notNull(value, "value");
    Validate.notNull(model, "data bundle");
    final InterpolationBoundedValues boundedValues = model.getBoundedValues(value);
    final Double x1 = boundedValues.getLowerBoundKey();
    final Double y1 = boundedValues.getLowerBoundValue();
    if (model.getLowerBoundIndex(value) == model.size() - 1) {
        return y1;
    }//from  w ww.j a  v a  2 s .c  o  m
    final Double x2 = boundedValues.getHigherBoundKey();
    final Double y2 = boundedValues.getHigherBoundValue();

    // nodes and values for the step interpolator
    final double[] nodes = new double[12];
    final double[] values = new double[12];
    nodes[0] = x1;
    values[0] = y1;

    // solver used to find the growth
    final BrentSolver solver = new BrentSolver();

    // definition of the function to minimize
    final Function1D<Double, Double> function = new Function1D<Double, Double>() {
        @SuppressWarnings("synthetic-access")
        @Override
        public Double evaluate(final Double x) {
            double result = y1;
            for (int loopmonth = 0; loopmonth < NB_MONTH; loopmonth++) {
                result = result * (1 + x + _seasonalValues[loopmonth]);
            }
            return result - y2;
        }
    };

    // the initial guess for the solver is the solution when all seasonal values are set to 0.
    final double initialGuess = Math.pow(y2 / y1, 1 / 12.0) - 1.0;

    // We solve the equation define by the function and use the result to calculate values, nodes are also calculates.
    final UnivariateRealFunction f = CommonsMathWrapper.wrapUnivariate(function);
    double growth;
    try {
        growth = solver.solve(f, -.5, .5, initialGuess);

        for (int loopmonth = 1; loopmonth < NB_MONTH; loopmonth++) {
            nodes[loopmonth] = x1 + loopmonth * (x2 - x1) / 12.0;
            values[loopmonth] = values[loopmonth - 1] * (1 + growth + _seasonalValues[loopmonth]);
        }
    } catch (final MaxIterationsExceededException ex) {
        // TODO Auto-generated catch block
        ex.printStackTrace();
    } catch (final FunctionEvaluationException ex) {
        // TODO Auto-generated catch block
        ex.printStackTrace();
    }

    final Interpolator1DDataBundle dataBundle = getDataBundleFromSortedArrays(nodes, values);
    final StepInterpolator1D stepInterpolator = new StepInterpolator1D();

    return stepInterpolator.interpolate(dataBundle, value);

}

From source file:org.renjin.stats.internals.optimize.Roots.java

/**
 * Searches the interval from lower to upper for a root (i.e., zero) of the function f with
 * respect to its first argument./*w  w  w .  j  a va 2  s .co m*/
 *
 * <p>
 * This internal primitive is used by the uniroot() function in the stats package.
 *
 * <p>
 * This implementation wraps the Commons Math {@link BrentSolver}; there are however
 *
 */
@Internal
public static DoubleVector zeroin2(@Current Context context, @Current Environment rho, Function fn,
        double lower, double upper, double fLower, double fUpper, double tol, int maximumIterations) {

    BrentSolver solver = new BrentSolver(maximumIterations, tol);

    double root;
    int iterations;
    double estimatedPrecision = DoubleVector.EPSILON; // not exposed by commons math impl

    try {
        root = solver.solve(maximumIterations, new UnivariateRealClosure(context, rho, fn), lower, upper);
        iterations = 1; // the Commons math impl doesn't expose this
    } catch (MaxIterationsExceededException e) {
        root = DoubleVector.NA;
        iterations = -1;
    } catch (FunctionEvaluationException e) {
        throw new EvalException(e);
    }

    return new DoubleArrayVector(root, iterations, estimatedPrecision);
}

From source file:uk.ac.diamond.scisoft.analysis.fitting.EllipseFitterTest.java

@Test
public void testOrthoDist() {

    AngleDerivativeFunction angleDerivative = new AngleDerivativeFunction();
    BrentSolver solver = new BrentSolver(BrentSolver.DEFAULT_ABSOLUTE_ACCURACY);
    double a = 10.2;
    double b = 3.1;
    final double twopi = 2 * Math.PI;
    double alpha = twopi * 10. / 360; // 0 to 2 pi
    angleDerivative.setRadii(a, b);//  ww w . jav a 2  s  .  co m
    angleDerivative.setAngle(alpha);

    //      final double ca = 0;
    //      final double cb = b-0.5;
    final double Xc = -5.; // Math.cos(alpha)*ca + Math.sin(alpha)*cb;
    final double Yc = 5.5; //Math.sin(alpha)*ca + Math.cos(alpha)*cb;

    angleDerivative.setCoordinate(Xc, Yc);
    try {
        // find quadrant to use
        double p = Math.atan2(Yc, Xc);
        if (p < 0)
            p += twopi;
        p -= alpha;
        final double end;
        final double halfpi = 0.5 * Math.PI;
        p /= halfpi;
        end = Math.ceil(p) * halfpi;
        final double angle = solver.solve(BrentSolver.DEFAULT_MAXIMUM_ITERATIONS, angleDerivative, end - halfpi,
                end);
        //         final double cos = Math.cos(angle);
        //         final double sin = Math.sin(angle);

        Assert.assertEquals("Angle found is not close enough", 1.930, angle, 0.001);
        //         double dx = a*cos + Xc;
        //         double dy = b*sin + Yc;
        //
        //         System.out.println("Bracket angle = " + Math.ceil(p));
        //         System.out.println("Delta angle = " + 180.*angle/Math.PI);
        //         System.out.println(dx + ", " + dy);
    } catch (MaxIterationsExceededException e) {
        // TODO
        System.err.println(e);
    } catch (FunctionEvaluationException e) {
        // TODO
        System.err.println(e);
    }

}