# Relative factorisation with scalar quantities

I'd like to find a natural way to tell mathematica that a given unknown in a polynomial should be treated as a number, unlike the other variables.

Typically I'd like to sum two polynomials in several variables, say

P[x,y,z]=x y^2 z + 2x y z^2 + x^2 y^2
Q[x,y,z]=x^2 y z - x y z^2 + x^2 z^2


with a scaling factor a on one of them, such that the output of P + a Q looks like;

x y^2 z + (2-a) x y z^2 + x^2 y^2 + a x^2 y z + a x^2 z^2


So mathematica should really interpret a as a number.

• This site relies on an economy of upvotes. Yet, you felt that the accepted answer was worth the checkmark, but not an upvote. Doesn't that strike you as strange? – rcollyer Jul 28 '15 at 14:39
• @ rcollyer; I guess I can't upvote before having 15 rep, so I did as best as I could to acknowledge that the answer was useful to me. – picop Jul 28 '15 at 14:41
• Weird. I was under the impression that you could upvote answers to your own question. My apologies, and a +1 because I liked the question. – rcollyer Jul 28 '15 at 14:45
• No worries ! (also thanks for allowing me to upvote on mathematica.SE) – picop Jul 28 '15 at 14:48

MonomialList may provide functionality you're looking for here.

P[x,y,z]=x y^2 z + 2x y z^2 + x^2 y^2;
Q[x,y,z]=x^2 y z - x y z^2 + x^2 z^2;
P[x,y,z]+a Q[x,y,z]//Expand


will yield

x^2 y^2 + a x^2 y z + x y^2 z + a x^2 z^2 + 2 x y z^2 - a x y z^2


Now, to get the factorization you're looking for,

MonomialList[x^2 y^2 + a x^2 y z + x y^2 z + a x^2 z^2 + 2 x y z^2 - a x y z^2, {x, y, z}]
Plus@@%


gives

{x^2 y^2, a x^2 y z, a x^2 z^2, x y^2 z, (2 - a) x y z^2}
x^2 y^2 + a x^2 y z + x y^2 z + a x^2 z^2 + (2 - a) x y z^2


Edit: I should also add that using Expand in this progression of steps is redundant if you're going to roll it up into one line, as MonomialList handles that functionality as well. I only used it here so you could see the polynomial in the form similar to your description. To generalize it as a function you'd do something like

Clear[FactorConstants]
FactorConstants[p_,vars_List]:=Plus@@MonomialList[p,vars]


Usage:

FactorConstants[P[x,y,z]+a Q[x,y,z],{x,y,z}]

x^2 y^2 + a x^2 y z + x y^2 z + a x^2 z^2 + (2 - a) x y z^2