C# 用mathdotnet求解线性方程组?

C# 用mathdotnet求解线性方程组?,c#,math.net,C#,Math.net,我想解方程,比如 (4-x)*2=(y-1)*10+2 x=y*2+1 这些方程式以字符串形式提供。 有没有办法用mathdotnet表达一个方程式?我只能找到写表达式的方法。可以,但我想这不是你想要的 可以处理符号表达式,尽管该项目处于早期阶段,尚未理解方程的概念。然而,我们仍然可以用它来解决像这样的简单系统,只需做一点工作——我们也可以手工完成 首先,让我们定义一个小函数来求解一个阶数为1的线性方程: using Expr = MathNet.Symbolics.Expression; E

我想解方程,比如

(4-x)*2=(y-1)*10+2

x=y*2+1

这些方程式以字符串形式提供。 有没有办法用mathdotnet表达一个方程式?我只能找到写表达式的方法。

可以,但我想这不是你想要的

可以处理符号表达式,尽管该项目处于早期阶段,尚未理解方程的概念。然而,我们仍然可以用它来解决像这样的简单系统,只需做一点工作——我们也可以手工完成

首先,让我们定义一个小函数来求解一个阶数为1的线性方程:

using Expr = MathNet.Symbolics.Expression;

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;
    }
}
然后我们可以用它来解决系统,如下所示:

// declare variables
var x = Expr.Symbol("x");
var y = Expr.Symbol("y");

// Parse left and right side of both equations
Expr aleft = Infix.ParseOrThrow("(4-x)*2");
Expr aright = Infix.ParseOrThrow("(y-1)*10+2");
Expr bleft = Infix.ParseOrThrow("x");
Expr bright = Infix.ParseOrThrow("y*2+1");

// Solve both equations to x
Expr ax = SolveSimpleRoot(x,aleft-aright); // "8 - 5*y"
Expr bx = SolveSimpleRoot(x,bleft-bright); // "1 + 2*y"

// Equate both terms of x, solve to y
Expr cy = SolveSimpleRoot(y,ax-bx); // "1"

// Substitute term of y into one of the terms of x
Expr cx = Algebraic.Expand(Structure.Substitute(y,cy,ax)); // "3"

// Print expression in Infix notation
Console.WriteLine(Infix.Print(cx)); // x=3
Console.WriteLine(Infix.Print(cy)); // y=1
嘿,克里斯托夫!能够按如下方式解决第一个示例:
((4-x)*2==(y-1)*10+2).IsolateVariable(x).AlgebraicExpand()
。是非常特别的,但它可以处理我抛出的许多表达式。期待着类似的符号!:-)