1

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?

kizzer
  • 150
  • 7

2 Answers2

1

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)));
Orace
  • 7,822
  • 30
  • 45
  • thank you very much for your help here! The LaTex tip is really useful and the Summands use may well end up being how I have to do it, if so I will come back and mark this as answered. – kizzer Feb 06 '20 at 14:41
  • Marked as the answer as from reading elsewhere this may very well be the only/best way to do this and perhaps some Regex could reinstall that +...as a result will be looking for a MathNet alternative – kizzer Feb 08 '20 at 09:23
0

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.

phv3773
  • 487
  • 4
  • 10
  • Thank you phv, however quoting the initial question: "I tried `.ToStringDescending()` function, in polynomials but was unable to get it working here." How are you converting from symbolics expressions to numerics polynomials? I instead wrote this: `string.Join(" ", StringYouWantReversing.Split(' ').Reverse());` after being inspired by @Orace – kizzer Feb 10 '20 at 18:38