在我的一个项目中,我想添加一个用户可以在公式中提供的功能,例如
sin (x + pi)/2 + 1
我在Java应用程序中使用它
/**
* The formula provided by the user
*/
private String formula; // = "sin (x + pi)/2 + 1"
/*
* Evaluates the formula and computes the result by using the
* given value for x
*/
public double calc(double x) {
Formula f = new Formula(formula);
f.setVar("x", x);
return f.calc();
// or something similar
}
如何计算数学表达式?
发布于 2011-11-15 16:36:31
还有一个基于Dijkstra's Shunting Yard
的表达式求值器exp4j。它可以在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();
当使用较新的API版本时,如0.4.8
Expression calc = new ExpressionBuilder("3 * sin(y) - 2 / (x - 2)")
.variable("x", x)
.variable("y", y)
.build();
double result1 = calc.evaluate();
还有一个在exp4j中使用定制函数的工具。
发布于 2011-08-31 22:38:49
这取决于你想要求值的表达式有多复杂,但对于简单的表达式,java有一个工作得很好的javascript引擎:
import javax.script.*;
public class EvalScript {
public static void main(String[] args) throws Exception {
// create a script engine manager
ScriptEngineManager factory = new ScriptEngineManager();
// create a JavaScript engine
ScriptEngine engine = factory.getEngineByName("JavaScript");
// evaluate JavaScript code from String
Object obj = engine.eval("1+2");
System.out.println( obj );
}
}
发布于 2017-04-21 04:30:36
很好的数学解析器,包含了广泛的数学集合-- mXparser --请看下面的例子:
示例1:
import org.mariuszgromada.math.mxparser.*;
...
...
Argument x = new Argument("x = pi");
Expression e = new Expression("sin(x + pi)/2 + 1", x);
mXparser.consolePrintln("Res 1: " + e.getExpressionString() + " = " + e.calculate());
x.setArgumentValue(2);
mXparser.consolePrintln("Res 2: " + e.getExpressionString() + " = " + e.calculate());
结果:
[mXparser-v.4.0.0] Res 1: sin(x + pi)/2 + 1 = 1.0
[mXparser-v.4.0.0] Res 2: sin(x + pi)/2 + 1 = 0.545351286587159
示例2:
import org.mariuszgromada.math.mxparser.*;
...
...
Function f = new Function("f(x) = sin(x + pi)/2 + 1");
Expression e = new Expression("f(pi)", f);
mXparser.consolePrintln("Res: " + e.getExpressionString() + " = " + e.calculate());
结果:
[mXparser-v.4.0.0] Res: f(pi) = 1.0
为了更好地理解,请关注mXparser tutorial和mXparser math collection。
最近发现-如果您想尝试语法(并查看高级用例),您可以下载由mXparser提供支持的Scalar Calculator app。
诚挚的问候
https://stackoverflow.com/questions/7258538
复制相似问题