无法使用Apache Commons Math库解决单变量函数

时间:2015-01-08 09:01:17

标签: java function math

我正在使用Apache Commons Math Library 3.4。我已经实现了一个单变量函数名PFunction。在我的Main课程中,我尝试解决2 * p * Math.log(p) / (p + 1) -ww-0.5

但是,我收到错误:

org.apache.commons.math3.exception.NoBracketingException: function values at endpoints do not have different signs, endpoints: [1, 1,000], values: [0.5, 14.302]
    at org.apache.commons.math3.analysis.solvers.BrentSolver.doSolve(BrentSolver.java:122)
    at org.apache.commons.math3.analysis.solvers.BaseAbstractUnivariateSolver.solve(BaseAbstractUnivariateSolver.java:195)
    at org.apache.commons.math3.analysis.solvers.BaseAbstractUnivariateSolver.solve(BaseAbstractUnivariateSolver.java:200)
    at Main.main(Main.java:43)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)

我尝试过其他求解器,例如穆勒的方法,他们显示相同的错误。另外,我发现w的正值,例如0.5,不会给我一个错误。谢谢你的帮助。

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

public class PFunction implements  UnivariateFunction {
    private double w;

    public PFunction(double w) {
        this.w = w;
    }

    @Override
    public double value(double p) {
        return 2 * p * Math.log(p) / (p + 1) -w;
    }
}

主要课程:

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

public class Main {
    public static void main(String[] args) {
        double p;
        UnivariateFunction univariateFunction = new PFunction(-0.5);
        BrentSolver brentSolver = new BrentSolver();

        try {
            p = brentSolver.solve(1000, univariateFunction, 1, 1000);
            System.out.println("Brent solver, p: " + p);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

1 个答案:

答案 0 :(得分:0)

我对此并不熟悉,但错误似乎很清楚。您的函数值在区间的两侧都具有相同的符号,因此不会被括起来。尝试使用不需要包围的AbstractUnivariateSolver子类。