Java:求解符号代数方程 [英] Java: solving symbolic algebraic equations
问题描述
我无法将此功能添加到我的计算器应用程序中.这是我的想法:
I'm having trouble adding this functionality to my calculator app. Here's what I had in mind:
我要解:2x = 5 + 4x
.
为了解决这个问题,如果我使用外部令牌库来解析方程,那是没有问题的,但是由于我的整个程序是围绕一个分流码解析器 (EXP4J) 构建的,它使事情变得复杂.你可能会说我可以只在特定情况下使用令牌解析器,但是当你考虑到我有使用 EXP4J 的 FUNCTIONS 时,它变得很纠结.
To solve this is no problem if I would use an external token library to parse the equation, but since my entire program is built around a shunting yard parser (EXP4J), it complicates things. You might say that I could just use the token parser for specific cases, but when you consider that I have FUNCTIONS using EXP4J, it becomes really tangled.
所以,虽然我可以通过简单地在这种特定情况下交替使用令牌解析器来使其适用于 2x = 5 + 4x
,但使用 EXP4J 的计算,例如:
So, while I could make it work for 2x = 5 + 4x
by simply alternating to a token parser for this specific case, calculations that use EXP4J, like:
2x = 5*exp4jfunc(x + 5,x) + cos(x)
完全超出我的范围.
有没有人知道如何解决这个问题?我什至不知道我的 CASIO 是如何解决这个问题的,因为它冻结在求解 x 方程上,例如 x = 9^x
...
Does anyone have any idea on how to get around this? I don't even know how my CASIO tackles this, as it freezes on solve-for-x equations like x = 9^x
...
推荐答案
使用 symja 库可以这样解决你的问题:
With the symja library you can solve your problem like this:
package org.matheclipse.core.examples;
import org.matheclipse.core.eval.ExprEvaluator;
import org.matheclipse.core.interfaces.IExpr;
import org.matheclipse.parser.client.SyntaxError;
import org.matheclipse.parser.client.math.MathException;
public class Solve2Example {
public static void main(String[] args) {
try {
ExprEvaluator util = new ExprEvaluator();
IExpr result = util.evaluate("Solve(2*x==5 + 4*x,x)");
// print: {{x->-5/2}}
System.out.println(result.toString());
result = util.evaluate("Roots(2*x==5+4*x, x)");
// print: x==-5/2
System.out.println(result.toString());
} catch (SyntaxError e) {
// catch Symja parser errors here
System.out.println(e.getMessage());
} catch (MathException me) {
// catch Symja math errors here
System.out.println(me.getMessage());
} catch (Exception e) {
e.printStackTrace();
}
}
}
您可以查看 Roots() 函数 解析后的 AST 如何转换以求解方程.
You can look into the implementation of the Roots() function how the parsed AST is transformed to solve the equation.
这篇关于Java:求解符号代数方程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!