# Optimal way to extract “positive part” of a multivariate polynomial

I've got multivariate polynomials with numerical coefficients, like e. g.

p - s - p q^2 s^2 + 3 r s^2 + 3 r^2 s^2 - p r^2 s^2 - 2 q r^2 s^2 - 2 r^3 s^2 + s^3


and I would like to take the sum of those monomials with positive coefficients only.

Although for my purposes

FromCoefficientRules[Select[CoefficientRules[poly],Last[#]>0&],Variables[poly]]


seems to be quick enough, it involves translating to another form and back, so I feel there must be a more optimal way to do it, probably using some tricks with the internal representation of polynomials.

Is there?

This will delete the terms written with a leading minus sign:

nixneg[p_Plus] := DeleteCases[p, _?InternalSyntacticNegativeQ];
nixneg[_?InternalSyntacticNegativeQ] := 0;  (* 1-term case: neg *)
nixneg[p_] := p;                             (* 1-term case: nonneg *)


OP's example:

nixneg[poly]  (* use nixneg[Expand@poly] if needed *)
(*  p + 3 r s^2 + 3 r^2 s^2 + s^3  *)


Deletes negative constant terms, too:

nixneg[poly + 100]
nixneg[poly - 100]
(*
100 + p + 3 r s^2 + 3 r^2 s^2 + s^3
p + 3 r s^2 + 3 r^2 s^2 + s^3
*)


Assuming poly is homogeneous (as in the example in the OP),

poly /. Times[_?Negative, _] -> 0

• Nice! But you mean without constant term rather than homogeneous, right? My polynomials might have constant terms, actually, but I am sure one can deal with them very quickly too – მამუკა ჯიბლაძე Aug 10 at 14:07
• @მამუკაჯიბლაძე oh, yes, I meant without constant term! – AccidentalFourierTransform Aug 10 at 14:18
• Sorry! - have to accept the most complete one – მამუკა ჯიბლაძე Aug 10 at 21:14
• @მამუკაჯიბლაძე no need to apologise, those are great answers too, clearly better than mine :-) – AccidentalFourierTransform Aug 10 at 21:19
exp = p - s - p q^2 s^2 + 3 r s^2 + 3 r^2 s^2 - p r^2 s^2 - 2 q r^2 s^2 - 2 r^3 s^2 + s^3


Few additional ways to use InternalSyntacticNegativeQ:

Select[Not @* InternalSyntacticNegativeQ] @ exp


p + 3 r s^2 + 3 r^2 s^2 + s^3