MathGroup Archive 2008

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: ordering of multivariate polynomial terms

  • To: mathgroup at smc.vnet.net
  • Subject: [mg86646] Re: ordering of multivariate polynomial terms
  • From: Szabolcs Horvát <szhorvat at gmail.com>
  • Date: Sat, 15 Mar 2008 17:46:01 -0500 (EST)
  • Organization: University of Bergen
  • References: <frg0d4$evn$1@smc.vnet.net>

Stefan Porubsky wrote:
> Hello,
> 
> how it is possible to rearrange the terms of a multivariate polynomial 
> in Standard or Traditional Form in such a way that the terms are ordered 
> according to the number of their variables, i.e. first the constant 
> term, then the group of terms depending on one of the variables, then 
> the group of terms depening on two variables, then the group of those 
> with three variables, etc.?
> 

It is not possible to do this because Plus has the Attribute orderless. 
  This means that Mathematica will automatically sort the terms of any 
sum using its built-in ordering rules.

Here's a function that returns a list of the terms sorted by degree:

sortPoly[poly_, vars_] := Module[{x, exp},
   exp[term_] := Exponent[term /. Alternatives @@ vars -> x, x];
   Sort[List @@ poly, exp[#1] >= exp[#2] &]
]

(The exp[] function returns the degree of a term.)

For example:

f = 2 + 5 x + 7 x^2 + 5 x^3 + x^4 + 4 y + 16 x y + 9 x^2 y + 4 x^3 y +
  10 y^2 + 15 x y^2 + 6 x^2 y^2 + 3 y^3 + 4 x y^3 + y^4

sortPoly[f, {x, y}]

{x^4, 4 x^3 y, 6 x^2 y^2, 4 x y^3, y^4, 5 x^3, 9 x^2 y,
  15 x y^2, 3 y^3, 7 x^2, 16 x y, 10 y^2, 5 x, 4 y, 2}

Now we can convert the list back to a sum, and use Hold to prevent 
automatic reordering.

Hold@Plus[##] & @@ %

Hold[x^4 + 4 x^3 y + 6 x^2 y^2 + 4 x y^3 + y^4 + 5 x^3 + 9 x^2 y +
   15 x y^2 + 3 y^3 + 7 x^2 + 16 x y + 10 y^2 + 5 x + 4 y + 2]

...

I'm not sure if I interpreted your request correctly.  Here's and 
alternative "exp" function that returns the number of different 
variables present in a term:

exp[term_] := Count[FreeQ[term, #] & /@ vars, False]

The full sortPoly:

sortPoly[poly_, vars_] := Module[{x, exp},
   exp[term_] := Count[FreeQ[term, #] & /@ vars, False];
   Sort[List @@ poly, exp[#1] <= exp[#2] &]
]

Now sortPoly[f, {x,y}] returns

{2, 5 x, 7 x^2, 5 x^3, x^4, 4 y, 10 y^2, 3 y^3, y^4, 16 x y, 9 x^2 y,
  4 x^3 y, 15 x y^2, 6 x^2 y^2, 4 x y^3}


  • Prev by Date: Re: Clearing selected variables
  • Next by Date: Re: Question on Sum[] function
  • Previous by thread: Re: ordering of multivariate polynomial terms
  • Next by thread: Re: Re: ordering of multivariate polynomial terms