5
$\begingroup$

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?

$\endgroup$
4
$\begingroup$

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
*)
$\endgroup$
5
$\begingroup$

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

poly /. Times[_?Negative, _] -> 0
$\endgroup$
  • $\begingroup$ 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 $\endgroup$ – მამუკა ჯიბლაძე Aug 10 at 14:07
  • $\begingroup$ @მამუკაჯიბლაძე oh, yes, I meant without constant term! $\endgroup$ – AccidentalFourierTransform Aug 10 at 14:18
  • $\begingroup$ Sorry! - have to accept the most complete one $\endgroup$ – მამუკა ჯიბლაძე Aug 10 at 21:14
  • $\begingroup$ @მამუკაჯიბლაძე no need to apologise, those are great answers too, clearly better than mine :-) $\endgroup$ – AccidentalFourierTransform Aug 10 at 21:19
4
$\begingroup$
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

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.