0
$\begingroup$

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.

$\endgroup$
2
  • 5
    $\begingroup$ Replace does only literal replacements. Try Simplify[a^2 + b^2 + 2*a*b + x, Assumptions -> (a + b)^2 == c] instead. $\endgroup$
    – MarcoB
    Jan 13, 2021 at 21:40
  • 1
    $\begingroup$ An algebraic approach: Last@PolynomialReduce[a^2 + b^2 + 2*a*b + x, {(a + b)^2 - c}, {a, b, c, x}]. (The goal of PolynomialReduce 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 also First@GroebnerBasis[{a^2 + b^2 + 2*a*b + x, (a + b)^2 - c}, {c, x}, {a, b}] $\endgroup$
    – Michael E2
    Jan 13, 2021 at 23:30

2 Answers 2

2
$\begingroup$

Try 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!

$\endgroup$
0
$\begingroup$

A simple method:

   a^2 + b^2 + 2*a*b + x /. Expand[(a + b)^2 -> c]
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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