20

我需要一个库来解析方程并给出输入的结果。

例如这样的:

String equation = "x + y + z";
Map<String, Integer> vars = new HashMap<String, Integer>();
vars.add("x", 2);
vars.add("y", 1),
vars.add("z", 3);
EquationSolver solver = new EquationSolver(equation, vars);
int result = solver.getResult();
System.out.println("result: " + result);

并评估为:6

是否有任何类型的 java 库可以为我做到这一点?

谢谢

4

5 回答 5

29

您可以利用 Java 1.6 的脚本功能:

import javax.script.*;
import java.util.*;

public class Main {
    public static void main(String[] args) throws Exception {
        ScriptEngine engine = new ScriptEngineManager().getEngineByName("JavaScript");
        Map<String, Object> vars = new HashMap<String, Object>();
        vars.put("x", 2);
        vars.put("y", 1);
        vars.put("z", 3);
        System.out.println("result = "+engine.eval("x + y + z", new SimpleBindings(vars)));
    }
}

产生:

result = 6.0

对于更复杂的表达式,JEP是一个不错的选择。

于 2011-01-13T15:56:37.500 回答
18

还有exp4j,一个基于 Dijkstra 的 Shutting Yard 的表达式评估器。它可以在 Apache License 2.0 下免费获得和再分发,大小只有 25kb,而且非常易于使用。

Calculable calc = new ExpressionBuilder("3 * sin(y) - 2 / (x - 2)")
        .withVariable("x", varX)
        .withVariable("y", varY)
        .build()
double result1=calc.calculate();

在exp4j中还有一个使用自定义函数的工具。

exp4j - 计算数学表达式

玩得开心!

于 2011-11-15T08:31:27.183 回答
3

试试mXparser,你会在下面找到用法示例:

import org.mariuszgromada.math.mxparser.*;
...
...
String equation = "x + y + z";
Argument x = new Argument("x = 2");
Argument y = new Argument("y = 1");
Argument z = new Argument("z = 3");
Expression solver = new Expression(equation, x, y, z);
double result1 = solver.calculate();
System.out.println("result 1: " + result1);
x.setArgumentValue(3);
y.setArgumentValue(4);
z.setArgumentValue(5);
double result2 = solver.calculate();
System.out.println("result 2: " + result2);

结果:

result 1: 6.0
result 2: 12.0

这里 mXparser 的优点是 mXparser 只预编译表达式一次,然后在参数值更改后,计算速度非常快。

遵循mXparser 教程mXparser 数学集合mXparser API

此外 - 该软件也使用 mXparser - 您可以学习语法Scalar Calculator 应用程序

问候

于 2017-04-24T17:58:25.057 回答
2

如果你想要高性能,我建议不要使用 exp4j,因为 CogitoLearning 类比 exp4j 快大约 2600 倍(经过 100 万次迭代测试),是的,你没看错。

通常,简单的表达式对于业务应用程序就足够了。因此,CogitoLearning 创建的库可能是更好的选择。

基准测试结果:

1000000 iterations to evaluate 200*(1+(pi/2))^2
Time Exp4J: 1.041117999977863E-5
Time JavaScript:4.532046999924487E-5 - 0.2297235664138545x slower than Exp4j
Time ExpCogit:  4.0000000000000036E-9 - 2602.794999944655x faster than Exp4j

对于 Cogito 库,请参阅http://cogitolearning.co.uk/docs/cogpar/index.html

请注意:对于评估 JavaScript 性能,测试用例并不完全是纯粹的,因为我没有为该用例使用预构建的表达式。

使用的基准代码:

public class TestParser {
    private static String exprStr = "200*(1+(pi/2))^2";

    /**
     * Exp4j
     */ 
    private static ExpressionBuilder eb =  new ExpressionBuilder(exprStr);

    /**
     * Cogit
     */
    private static Parser parser = new Parser();
    private static ExpressionNode expr = parser.parse(exprStr);

    /**
     * JavaScript 
     */
    private static ScriptEngine engine = new ScriptEngineManager().getEngineByName("JavaScript");
    private static Map<String, Object> vars = new HashMap<String, Object>();

    public static void main(String[] args) throws UnknownFunctionException, UnparsableExpressionException, ScriptException {
        int n = 1000000;

        double t1 = 0d; 
        for(int i=1; i!=n; i++) {
            t1+=getCalcTimeExp4J();
        }
        double r1=t1/n;

        double t2 = 0d; 
        for(int i=1; i!=n; i++) {
            t2+=getCalcTimeCogit();
        }
        double r2=t2/n;

        double t3 = 0d; 
        for(int i=1; i!=n; i++) {
            t3+=getCalcTimeJavaScriptEngine();
        }
        double r3=t3/n;     

        System.out.println(n + " iterations to evaluate " + exprStr);
        System.out.println("Time Exp4J:\t" + r1);

        System.out.println("Time JavaScript:" + r3 + " - " + r1/r3 + "x slower than Exp4j");
        System.out.println("Time ExpCogit:\t" + r2 + " - " + r1/r2 + "x faster than Exp4j");

    }

    private static double getCalcTimeJavaScriptEngine() throws ScriptException {
        long t = Util.nanotime();

        vars.put("pi", Math.PI); 
        //Note that we're actually not using a pre-build expression here.
        engine.eval(exprStr, new SimpleBindings(vars)); 

        return(Util.nanotimeToSeconds(t));
    }

    private static double getCalcTimeCogit() {
        long t = Util.nanotime();

        expr.accept(new SetVariable("pi", Math.PI));
        double r = expr.getValue();

        return(Util.nanotimeToSeconds(t));
    }           

    private static double getCalcTimeExp4J() throws UnknownFunctionException, UnparsableExpressionException {
        long t = Util.nanotime();
        Calculable calc = eb.withVariable("pi", Math.PI).build();
        double r = calc.calculate();

        return(Util.nanotimeToSeconds(t));
    }
}
于 2014-05-31T15:27:24.207 回答
0

从被问到这个问题的八年后:如果你不想重新发明轮子,那里有许多奇特的数学解析器。

我几年前写过一个,它支持算术运算、方程求解、微积分、积分、基本统计、函数/公式定义、绘图等。

它被称为ParserNG及其开源。

评估表达式很简单:

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

    result: 43.16981132075472

或者使用变量并计算简单的表达式:

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

或使用功能:

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

或评估给定点的导数(注意它在幕后进行符号微分(不是数值),因此准确性不受数值近似误差的限制):

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

 result: 38.66253179403897

它在 x=3 处微分x^3 * ln(x)一次。您现在可以区分的次数是 1。

或数值积分:

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

result: 7.999999999998261... approx: 8

这个解析器速度相当快并且有很多其他的功能。

免责声明:ParserNG 由我编写。

于 2019-04-25T17:08:58.903 回答