How can I replace small expressions in larger expressions?
Simple example
Replace[a^2 + b^2 + 2*a*b + x, (a + b)^2 -> c]
I want to get c + x
but the output is a^2 + b^2 + 2*a*b + x
.
Mathematica Stack Exchange is a question and answer site for users of Wolfram Mathematica. It only takes a minute to sign up.
Sign up to join this communityTry this.
First:
s = Solve[(a + b)^2 == c, a][[1, 1]]
(* a -> -b - Sqrt[c] *)
second:
a^2 + b^2 + 2*a*b + x /. s // Simplify
(* c + x *)
Have fun!
A simple method:
a^2 + b^2 + 2*a*b + x /. Expand[(a + b)^2 -> c]
Replace
does only literal replacements. TrySimplify[a^2 + b^2 + 2*a*b + x, Assumptions -> (a + b)^2 == c]
instead. $\endgroup$Last@PolynomialReduce[a^2 + b^2 + 2*a*b + x, {(a + b)^2 - c}, {a, b, c, x}]
. (The goal ofPolynomialReduce
is not replacement, and, while it works here, it may not work in every instance. OTOH, depending on what the general goal is, if there is a more general goal, it may be more appropriate than replacement, since it is a quite common algebraic operation.) With a similar caveat, there's alsoFirst@GroebnerBasis[{a^2 + b^2 + 2*a*b + x, (a + b)^2 - c}, {c, x}, {a, b}]
$\endgroup$