# Simplify polynomials with simple subfactors

I am trying to simplify expressions such as

poly = 1 + (-2 + 4 a^2) x^2 + x^4


to the form

polySimple = (1-x^2)^2 + 4 a^2 x^2


Applying Simplify to poly does not give polySimple, even when I define

f[e_] := StringLength[ToString[InputForm[e]]]


and then try

Simplify[poly, ComplexityFunction -> f]


Note that f[poly]=26, while f[polySimple]=23, so I would have thought the above would have worked. Any ideas on how to get polySimple?

• For this simple example you can use Collect[poly,a,Simplify]. The behaviour of Simplify is quite mysterious to me. For example, the intermediate result 1 - 2 x^2 + 4 a^2 x^2 + x^4 has complexity 27, so we append f[1-2 x^2+4 a^2 x^2+x^4]=25 by hand, but the result is still not polySimple. I guess that there are more involved things like attributes and inner definitions influcing the intermediate steps. Oct 17, 2022 at 19:24
• Thanks! That does work for the simple example. I note that my original problem was to simplify a rational fraction where the polynomials in the numerator and denominator had the structure of poly (but were different ones). Your solution works separately for the numerator and denominator, but not when naively applied to the rational polynomial. (The "Collect" variable was the same in both cases.) So it's still a bit mysterious.... Oct 17, 2022 at 21:26
• Try setting f[e_]:=(Sow[e];StringLength[ToString[InputForm[e]]]) and then DeleteDuplicates[ClearSystemCache[];Reap[Simplify[1+(-2+4*a^2)*x^2+x^4,ComplexityFunction->f]][[2,1]]]. If I interpret the result correctly, the expression that you are suggesting is never tried. It makes sense that not all expressions are tried. You could perhaps have it generate more expressions using TransformationFunctions -> .... Maybe someone more knowledgeable will tell us. Oct 17, 2022 at 22:53
• You could add @yurie 's Collect to the transformation functions, as in f[e_]:=StringLength[ToString[InputForm[e]]]; t[e_]:=Collect[e,a,Simplify]; Simplify[poly,ComplexityFunction->f,TransformationFunctions->{Automatic,t}]. Oct 17, 2022 at 23:08

poly = 1 + (-2 + 4 a^2) x^2 + x^4
Expand[poly]


1 - 2 x^2 + 4 a^2 x^2 + x^4

ResourceFunction["CompleteSquare"][Expand@poly, x]


4 a^2 x^2 + (-1 + x^2)^2

• Thanks! This answer comes out of left field for me. Can you explain more? I looked up "ResourceFunction" and it seems it "finds" a user function (?) that happens to know how to "complete a square" in this context. Is that right? If so, where/what is this function? Oct 18, 2022 at 20:31
• resources.wolframcloud.com/FunctionRepository/resources/… . I learned about it from this forum. Can't say I know much about its internals.
– Syed
Oct 19, 2022 at 5:38