Algebra equation parser for java

后端 未结 5 729
渐次进展
渐次进展 2020-12-01 14:43

I need a library to be able to parse an equation an give me the result giving the inputs.

For example something like this:

String equation = \"x + y          


        
5条回答
  •  囚心锁ツ
    2020-12-01 14:47

    Eight years into the future from when this question was asked: If you don't want to re-invent the wheel, there are many exotic math parsers out there.

    There is one that I wrote years ago which supports arithmetic operations, equation solving, differential calculus, integral calculus, basic statistics, function/formula definition, graphing, etc.

    Its called ParserNG and its open-source.

    Evaluating an expression is as simple as:

        MathExpression expr = new MathExpression("(34+32)-44/(8+9(3+2))-22"); 
        System.out.println("result: " + expr.solve());
    
        result: 43.16981132075472
    

    Or using variables and calculating simple expressions:

     MathExpression expr = new MathExpression("r=3;P=2*pi*r;"); 
    System.out.println("result: " + expr.getValue("P"));
    

    Or using functions:

    MathExpression expr = new MathExpression("f(x)=39*sin(x^2)+x^3*cos(x);f(3)"); 
    System.out.println("result: " + expr.solve());
    
    result: -10.65717648378352
    

    Or to evaluate the derivative at a given point(Note it does symbolic differentiation(not numerical) behind the scenes, so the accuracy is not limited by the errors of numerical approximations):

    MathExpression expr = new MathExpression("f(x)=x^3*ln(x); diff(f,3,1)"); 
    System.out.println("result: " + expr.solve());
    
     result: 38.66253179403897
    

    Which differentiates x^3 * ln(x) once at x=3. The number of times you can differentiate is 1 for now.

    or for Numerical Integration:

    MathExpression expr = new MathExpression("f(x)=2*x; intg(f,1,3)"); 
    System.out.println("result: " + expr.solve());
    
    result: 7.999999999998261... approx: 8
    

    This parser is decently fast and has lots of other functionality.

    DISCLAIMER: ParserNG is authored by me.

提交回复
热议问题