I want to gather the complex-conjugates that are in a list, but with an exception: only if the imaginary part isn't zero.
For example:
poly = 2 - 2 x - x^2 + x^4
roots = x /. Solve[poly == 0, x]
GatherBy[roots, {Re[#], Abs[Im[#]]} &]
Gives:
{{-1 - i, -1 + i}, {1, 1}}
So here indeed the conjugates -1-i and -1+i are combined, which is what I want. But that also happens for 1 and 1, which I don't want to happen because there is no imaginary part.
So the desired output is:
{{-1 - i, -1 + i}, {1}, {1}}
And this idea should work with any polynomial, not only with this specific example.
Any suggestions?
GatherBy[roots, {Re@#, If[# == 0, RandomReal[{0, 1}], #] &@Abs@Im@#} &]
$\endgroup$ClearAll[f]; f[0] := RandomReal[{0, 1}]; GatherBy[roots, {Re@#, f@Abs@Im@#} &]
$\endgroup$