Optimal way to extract "positive part" of a multivariate polynomial
Assuming poly
is homogeneous (as in the example in the OP),
poly /. Times[_?Negative, _] -> 0
This will delete the terms written with a leading minus sign:
nixneg[p_Plus] := DeleteCases[p, _?Internal`SyntacticNegativeQ];
nixneg[_?Internal`SyntacticNegativeQ] := 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
*)
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 Internal`SyntacticNegativeQ
:
Select[Not @* Internal`SyntacticNegativeQ] @ exp
p + 3 r s^2 + 3 r^2 s^2 + s^3