Search code examples
javaapache-commons-math

Apache Common Maths - Univariate Function Solver


I am trying to solve the following mathematical equation for "V" using the apache-commons-math solver.

Equation :

V = log(X/ (V-1))

Following is the MWE;

import org.apache.commons.math3.analysis.UnivariateFunction;
import org.apache.commons.math3.analysis.solvers.*;

public class Test {
    public static void main(String[] args) {

        UnivariateFunction function = v ->  v - Math.log( (9/(v-1)) );
        UnivariateSolver solver = new BrentSolver();
        double c = solver.solve(100, function, -10.0, 10.0, 0);
        System.out.println(c);
    }
}

However, I get the following error;

Exception in thread "main" org.apache.commons.math3.exception.NoBracketingException: function values at endpoints do not have different signs, endpoints: [-10, 10], values: [�, 10]

I have looked around the internet to solve it but so far no success. I am looking for an MWE to solve "V", any help will be highly appreciated.


Solution

  • The BrentSolver only works with univariate functions over the real numbers. The real number support for the function f(v) = v - log(c / (v - 1)) is (1, Infinity). If v is less than or equal to 1, then the function evaluates to a complex number.

    The solver is failing because it tries to evaluate the function at -10 and receives NaN at the value. This causes the bracketing exception to occur because the sign of NaN is indeterminate.

    So, in order for the solver to work you must provide an initial lower bound that is included in the real number support. Something just greater than 1 should suffice.