Search code examples
c#math.netmathnet-numericsmathdotnet-symbolics

MathNet.Symbolics Algebraic.Expand in descending order?


With MathNet.Symbolics library, I try to print a polynomial with a descending power order:

using mse = MathNet.Symbolics.Expression;
using MathNet.Symbolics;

public void Symbolics()
{
    var x1 = 2;
    var y2 = 3;
    var x2 = 4;

    // (2a+3)(a-4)

    var x = mse.Symbol("x");
    var a = mse.Symbol("x");
    var y = mse.Symbol("y");

    var expression = (x1 * a + y2) * (a - x2);
    var expanded = Algebraic.Expand(expression);
    var firstResult = Infix.Format(expanded);


    Debug.Log("Expression: " + expression);
    Debug.Log("Expanded: " + firstResult);
}

The current output is in ascending order: -12 - 5*x + 2*x^2, but I want it the other way. I tried .ToStringDescending() function, in polynomials but was unable to get it working here.

Also, output to Latex would be useful if possible but not essential.

How do I have have the result of Algebraic.Expand in descending not ascending order?


Solution

  • You can have Latex output with the corresponding format provider:

    Console.WriteLine("LaTeX.Format: " + LaTeX.Format(expanded));
    

    The best I can get is to use Summands to get them and the reverse the list. Sadly the + sign is lost in the process:

    Console.WriteLine("Summands: " + string.Join("+", Algebraic.Summands(expanded).Reverse().Select(Infix.Format)));