MathNet.Symbolics Algebraic.Expand in descending order?

341 views Asked by At

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?

2

There are 2 answers

2
Orace On BEST ANSWER

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)));
1
phv3773 On

Numerics.Polynomial has ToString() that returns the string in ascending form and

ToStringDescending(string format, IFormatProvider formatProvider) Format the polynomial in descending order, e.g. "x^3 + 2.0x^2 - 4.3"

that returns the string in descending form.