       Re: Collecting Positive and Negative Terms

• To: mathgroup at smc.vnet.net
• Subject: [mg111741] Re: Collecting Positive and Negative Terms
• From: TJR <tilminator at googlemail.com>
• Date: Thu, 12 Aug 2010 05:27:36 -0400 (EDT)
• References: <i3tnsg\$s5l\$1@smc.vnet.net>

```On 11 Aug., 10:44, Michael Knudsen <micknud... at gmail.com> wrote:
> Hi,
>
> I'm currently doing calculations often involving very large
> expressions with a lot of unknown parameters. To investigate whether
> an expression is positive or negative, I usually expand it using the
> Expand command and manually copy and paste the positive and negative
> terms into new expressions and simplify them using FullSimplify. In my
> case it often turns out that comparing the two is much easier than
> looking at the entire expression as a whole.
>
> However, it's very cumbersome to do all this manually. Is there an
> easy way in Mathematica to pick out terms begging with + (or -) in a
> sum?
>
> Thanks,
> Michael Knudsen

It's a hard problem in general, but I suppose you know a lot about
stuff that occurs in your specific application. So use pattern
matching.

separatePositiveNegative::usage= "separatePositiveNegative[hugesum]
expands a hugesum, turns it into a list of summands, and then subsums
those summands deemend positive / negative by myPositiveQ. Returns
{...positive parital sum ..., ... negative partial sum...}.";

Clear[separatePositiveNegative];
separatePositiveNegative[hugesum_] := Module[{sowReapKey, f},
f[sowReapKey[_], list_] := Plus @@ list;

hugesum //
Expand //
If[Head[#] == Plus, List @@ #, {#}] & //
Reap[Map[
If[myPositiveQ[#], Sow[#, sowReapKey["+"]];,
Sow[#, sowReapKey["-"]];] &,
#], sowReapKey[_], f][] &
];

myPositiveQ::usage="myPositiveQ[expr_] tests if expr is positive or
negative. Always returns True/False, but not always correctly. The
algorithm relies on pattern matching. expr is broken up recursively,
and the smallest bits are guessed positive/negative. Modify the
definition of myPositiveQHelper to tweak the patterns.";
Clear[myPositiveQ, myPositiveQHelper];
myPositiveQ[
expr_] := (expr //
myPositiveQHelper) /. {myPositiveQHelper -> ((Print[
"deemed positive by myPositiveQHelper: ", #]; 1) &)} //
Positive;
myPositiveQHelper[Times[exp1_, exp2__]] :=
Times @@ Map[myPositiveQHelper, {exp1, exp2}];
myPositiveQHelper[Power[base_, exponent_/;!OddQ[exponent]]] = 1;(*no
complex numbers*)
myPositiveQHelper[Power[base_, exponent_/;OddQ[exponent]]] :=
myPositiveQHelper[base];(*no complex numbers*)

myPositiveQHelper[exp_Symbol] = 1;
(*override as needed, e.g. myPositiveQHelper[alwaysNegative]=-1; *)

myPositiveQHelper[exp_ /; NumericQ[exp]] := Sign[exp];

```

• Prev by Date: Re: Custom dialog during evaluation
• Next by Date: Re: A new graphic user interface
• Previous by thread: Re: Collecting Positive and Negative Terms
• Next by thread: Re: Collecting Positive and Negative Terms