我尝试修改给定here的代码来解决x值的线性方程。如
(3 * X + 7)/ 3 +(2 * X)/ 9 =10分之6
首先将其分为左右两个表达式,然后使用" SolveSimpleRoot"它有效地给出了x的值。但如果线性方程是以
的形式写的(3 + 2 * x)/(5 * x-2)= 7,你可以在整个(5 * x-2)内多次使用,并且确实是线性的,然后代码失败
public void solveForX()
{
string eqn = "(3*x+7)/3+(2*x)/9=6/10"
string[] expString = eqn.Split('=');
var x = MathNet.Symbolics.Expression.Symbol("x");
MathNet.Symbolics.Expression aleft = MathNet.Symbolics.Infix.ParseOrThrow(expString[0]);
MathNet.Symbolics.Expression aright = MathNet.Symbolics.Infix.ParseOrThrow(expString[1]);
ans = SolveSimpleRoot(x, aleft - aright);
SelectionInsertText(MathNet.Symbolics.Infix.Print(cx));
}
private MathNet.Symbolics.Expression SolveSimpleRoot(MathNet.Symbolics.Expression variable, MathNet.Symbolics.Expression expr)
{
// try to bring expression into polynomial form
MathNet.Symbolics.Expression simple = MathNet.Symbolics.Algebraic.Expand(MathNet.Symbolics.Rational.Simplify(variable, expr));
// extract coefficients, solve known forms of order up to 1
MathNet.Symbolics.Expression[] coeff = MathNet.Symbolics.Polynomial.Coefficients(variable, simple);
switch (coeff.Length)
{
case 1: return variable;
case 2: return MathNet.Symbolics.Rational.Simplify(variable, MathNet.Symbolics.Algebraic.Expand(-coeff[0] / coeff[1]));
default: return MathNet.Symbolics.Expression.Undefined;
}
}
错误:
输入序列为空。参数名称:source
如果表达式像(2x + 7)/ x = 2,它仍然无法解决,它仍然扩展为线性。
知道为什么吗?
代码基本上是:
grep -i 'test' -R .
答案 0 :(得分:2)
你可以通过将双方乘以分母来扩展它以支持这种理性情况(因此有效地仅使用分子,Rational.Numerator
):
private Expr SolveSimpleRoot(Expr variable, Expr expr)
{
// try to bring expression into polynomial form
Expr simple = Algebraic.Expand(Rational.Numerator(Rational.Simplify(variable, expr)));
// extract coefficients, solve known forms of order up to 1
Expr[] coeff = Polynomial.Coefficients(variable, simple);
switch (coeff.Length)
{
case 1: return Expr.Zero.Equals(coeff[0]) ? variable : Expr.Undefined;
case 2: return Rational.Simplify(variable, Algebraic.Expand(-coeff[0] / coeff[1]));
default: return Expr.Undefined;
}
}
这样它也可以处理(3+2*x)/(5*x-2)=7
。如果在这种情况下系数不等于零,我还修复了案例1以返回undefined,因此另一个例子(2*x+7)/x=2
的解决方案将按预期未定义。
当然,这仍然是一个非常简单的例行程序,无法处理任何更高阶的问题。