8
$\begingroup$

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?

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

2 Answers 2

7
$\begingroup$

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}} *)
$\endgroup$
1
  • $\begingroup$ Complement[] should allow for not having to apply tests to the same list twice. $\endgroup$ Commented Jul 12, 2016 at 21:20
3
$\begingroup$

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}} *)
$\endgroup$
3
  • $\begingroup$ f[0] := Unique[x] :) $\endgroup$
    – Kuba
    Commented Oct 29, 2015 at 19:58
  • $\begingroup$ @Kuba but that one will define a new symbol name at each invocation potentially resulting in memory problems ... $\endgroup$ Commented Oct 29, 2015 at 20:01
  • $\begingroup$ Add Temporary attribute :P Yes I know it's not great but it wasn't my intention :) $\endgroup$
    – Kuba
    Commented Oct 29, 2015 at 20:02

Your Answer

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

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