# Exception with GatherBy: gathering complex conjugates

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?

• Do you care about the order? – Kuba Oct 29 '15 at 19:02
• @Kuba No, as long as the complex-conjugates are gathered together. – GambitSquared Oct 29 '15 at 19:08
• Dirty trick GatherBy[roots, {Re@#, If[# == 0, RandomReal[{0, 1}], #] &@Abs@Im@#} &] – Dr. belisarius Oct 29 '15 at 19:30
• @belisariusisforth Thank you! Maybe it can also be done in a more elegant way? – GambitSquared Oct 29 '15 at 19:34
• Not really sure if this could be considered "more elegant" ClearAll[f]; f[0] := RandomReal[{0, 1}]; GatherBy[roots, {Re@#, f@Abs@Im@#} &] – Dr. belisarius Oct 29 '15 at 19:41

Elegant this may not be, but it does not rely on uniquely generate symbols / numbers. Using the OP's definitions:

Join[
GatherBy[Cases[roots, n_ /; Im[n] != 0], {Re[#], Abs@Im[#]} &],
DeleteCases[roots, n_ /; Im[n] != 0]
] /. n_ /; Im[n] == 0 -> {n}

(* Out: {{-1 - I, -1 + I}, {1}, {1}} *)

• Complement[] should allow for not having to apply tests to the same list twice. – J. M.'s ennui Jul 12 '16 at 21:20

Until someone comes out with an elegant one:

ClearAll[f];
f[0] := RandomReal[{0, 1}]
GatherBy[roots, {Re@#, f@Abs@Im@#} &]

(* {{-1 - I, -1 + I}, {1}, {1}} *)

• f[0] := Unique[x] :) – Kuba Oct 29 '15 at 19:58
• @Kuba but that one will define a new symbol name at each invocation potentially resulting in memory problems ... – Dr. belisarius Oct 29 '15 at 20:01
• Add Temporary attribute :P Yes I know it's not great but it wasn't my intention :) – Kuba Oct 29 '15 at 20:02