7
$\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$
  • $\begingroup$ Do you care about the order? $\endgroup$ – Kuba Oct 29 '15 at 19:02
  • $\begingroup$ @Kuba No, as long as the complex-conjugates are gathered together. $\endgroup$ – GambitSquared Oct 29 '15 at 19:08
  • $\begingroup$ Dirty trick GatherBy[roots, {Re@#, If[# == 0, RandomReal[{0, 1}], #] &@Abs@Im@#} &] $\endgroup$ – Dr. belisarius Oct 29 '15 at 19:30
  • $\begingroup$ @belisariusisforth Thank you! Maybe it can also be done in a more elegant way? $\endgroup$ – GambitSquared Oct 29 '15 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$ – Dr. belisarius Oct 29 '15 at 19:41
6
$\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$
  • $\begingroup$ Complement[] should allow for not having to apply tests to the same list twice. $\endgroup$ – J. M. will be back soon Jul 12 '16 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$
  • $\begingroup$ f[0] := Unique[x] :) $\endgroup$ – Kuba Oct 29 '15 at 19:58
  • $\begingroup$ @Kuba but that one will define a new symbol name at each invocation potentially resulting in memory problems ... $\endgroup$ – Dr. belisarius Oct 29 '15 at 20:01
  • $\begingroup$ Add Temporary attribute :P Yes I know it's not great but it wasn't my intention :) $\endgroup$ – Kuba Oct 29 '15 at 20:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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