How do I tell mathematica to do this replacement smartly? (or how do I get smarter at telling mathematica to do what i want)
expr = b + c d + ec + 2 a;
expr /. a + b :> 1
Out = 2 a + b + c d + ec
I expect the answer to be a + cd + ec + 1
. And before someone suggests, I don't want to do a :> 1 - b
, because for aesthetic purposes, I'd like to have both a
and b
in my equation as long as the a+b = 1
simplification cannot be made.
In addition, how do I get it to replace all instances of 1-b
, -b+1
or -1+b
, b-1
with a
or -a
respectively and vice versa?
Here's an example for this part:
expr = b + c (1 - a) + (-1 + b)(a - 1) + (1 -a -b) d + 2 a
For the first case, you might consider:
For the second case, consider:
and:
You can use a customised version of
FullSimplify
by supplying your own transformations toFullSimplify
and let it figure out the details:equivs/.Equal->Subtract
turns given equations into expressions equal to zero (e.g.a+b==1
->a+b-1
).Flatten@Map[{#,-#}&, ]
then constructs also negated versions and flattens them into a single list.Function[x,x-#]& /@
turns the zero expressions into functions, which subtract the zero expressions (the#
) from what is later given to them (x
) byFullSimplify
.It may be necessary to specify your own
ComplexityFunction
forFullSimplify
, too, if your idea of simple differs fromFullSimplify
's defaultComplexityFunction
(which is roughly equivalent toLeafCount
), e.g.:In your example case, the default
ComplexityFunction
works fine, though.