I'm using the MathNet.Symbolics
library to simplify an algebraic formulas like
string f = Infix.Print(Infix.ParseOrThrow("L+H+L+H"))
And I correctly get f="2*L+2*H"
My problem arise when I need to subtract two of these formulas:
string f = Infix.Print(Infix.ParseOrThrow("L+H+L+H - (L+H)"))
And here I get f="2*L+2*H - (L+H)"
instead of (L+H)
What should I do to get the correct simplification?
Math.NET Symbolics always applies auto-simplification when constructing an expression, such that a denormalized form cannot even exist. This is essential to keep the algebraic algorithm complexity low, but is intentionally very limited. This is really more a term normalization, not a simplification.
The expression 2*H + 2*L - (H + L)
is technically indeed in normalized/auto-simplified form, but this may be more obvious when using Infix.PrintStrict
which is much less readable but shows exactly how the expression is represented internally: 2*H + 2*L + (-1)*(H + L)
.
There are quite a few algebraic routines that you can use to manipulate and simplify such expressions, in this case a simple algebraic expansions will do the trick:
var e1 = Infix.ParseOrThrow("L+H+L+H");
var e2 = Infix.ParseOrThrow("L+H");
var e3 = e1 - e2;
// or: var e3 = Infix.ParseOrThrow("L+H+L+H - (L+H)");
var expanded = Algebraic.Expand(e3);
Infix.Print(expanded); // prints "H + L"