TransWikia.com

How to use Collect to group negative terms?

Mathematica Asked by ockin on December 30, 2020

For example, I have: $-d^2-k^{d+1}+d k^d+d+k-1$.
I want to get: $-left(d^2+k^{d+1}+1right)+d k^d+d+k$.

One Answer

Test example:

SeedRandom[0];
poly = FromDigits[RandomInteger[{-5, 5}, 10], x]
(*  1 - 5 x + 3 x^2 + x^8 (2 + 5 x) + x^4 (-4 - 3 x + (3 - 5 x) x^2)  *)

The problem is that if you separate the added and subtracted terms, when it is evaluated, the minus sign is automatically distributed and the terms sorted (since Plus has the Attribute Orderless).

1 + 3 x^2 + 3 x^6 + 2 x^8 + 5 x^9 - (5 x^7 + 3 x^5 + 4 x^4 + 5 x)
(*  1 - 5 x + 3 x^2 - 4 x^4 - 3 x^5 + 3 x^6 - 5 x^7 + 2 x^8 + 5 x^9  *)

For output formatting: You can prevent Plus from being evaluated and sorting the monomials. This is inconvenient for further computation — I would just let the polynomial be reordered. However, for making a human-readable presentation, it can be done with Defer or HoldForm. Here is one way:

Plus @@ KeyValueMap[
  # /. {False -> #2, True -> -Defer@Evaluate[-#2]} &,
  Total /@ GroupBy[MonomialList[poly], Internal`SyntacticNegativeQ]
  ]
(*  1 + 3 x^2 + 3 x^6 + 2 x^8 + 5 x^9 - (5 x + 4 x^4 + 3 x^5 + 5 x^7)  *)

Correct answer by Michael E2 on December 30, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP