5

What is the easiest or fastest way to extract the homogeneous part of a polynomial in Mathematica. For instance, if there were a function homog_part[f,n], I could use it to extract the second, first and zeroth degree homogeneous part of $f=x^2+y^2+xy+x+y+7$ by writing homog_part[f,2] to get $x^2+y^2+xy$, homog_part[f,1] to get $x+y$ and homog_part[f,0] to get $7$.

I was thinking of using Series, but here you would give individual degrees of each variable while for the homogeneous part you need the total degree.

J. M.'s missing motivation
  • 124,525
  • 11
  • 401
  • 574
quantum
  • 287
  • 1
  • 6
  • 3
    A question like this really should be accompanied by test input in cut-and-pasteable form. – Daniel Lichtblau Oct 29 '17 at 14:48
  • @Daniel. Apologies. I agree. Some of the answer have these input so I will not add this in the question anymore. But I will keep this in mind for future reference/questions. – quantum May 16 '18 at 14:15

3 Answers3

8

SeriesCoefficient is useful for this. We just multiply all variables by a new variable and extract a degree term in that.

homogeneousPart[poly_, vars_, deg_] := 
 Module[{t}, 
  SeriesCoefficient[poly /. Thread[vars -> t*vars], {t, 0, deg}] /. 
   t -> 1]

Example:

pol = x^2 + y^2 + x*y + x + y + 7;

Table[homogeneousPart[pol, {x, y}, j], {j, 3, 0, -1}]

(* Out[6]= {0, x^2 + x y + y^2, x + y, 7} *)
J. M.'s missing motivation
  • 124,525
  • 11
  • 401
  • 574
Daniel Lichtblau
  • 58,970
  • 2
  • 101
  • 199
7
f[x_, y_] = x^2 + y^2 + x y + x + y + 7;
homoPart = Total[Pick[MonomialList[#], Total[CoefficientRules[#][[All, 1]], {2}], #2]] &;
homoPart[f[x, y], #] & /@ Range[0, 3]

{7, x + y, x^2 + x y + y^2, 0}

Coolwater
  • 20,257
  • 3
  • 35
  • 64
4
hp[f_, n_] := 
 Total@Cases[{Plus @@ #1, #2 Inner[Power, Variables[f], #1, Times, 
        1]} & @@@ CoefficientRules[f], {n, w_} :> w]

e.g. hp[f[x,y],#]&/Range[0,2] yields {7, x + y, x^2 + x y + y^2}

or hp[x^3 + 3 x^2 y + 2, #] & /@ Range[0, 3] yields {2, 0, 0, x^3 + 3 x^2 y}

ubpdqn
  • 60,617
  • 3
  • 59
  • 148