3
$\begingroup$

I have a very long list ss, and I want to make sure that all complex numbers and their conjugates exist inside the list. Below is a representative example.

ss1 = Table[RandomComplex[], {10}]
ss2 = Conjugate[ss1];
ss = Join[{ss1, ss2}] // Flatten;
cnt=Count[MemberQ[ss, Conjugate[#]] & /@ ss, False]

The problem with the above code is that it takes very long time. The length of my ss is around 80k. Is there a better and faster approach to this problem.

Thanks

$\endgroup$
  • $\begingroup$ Does the list only have complex numbers? $\endgroup$ – Carl Woll Dec 19 '17 at 21:32
  • $\begingroup$ yes, only complex numbers. $\endgroup$ – qahtah Dec 19 '17 at 21:35
  • $\begingroup$ "I want to make sure that all complex numbers and their conjugates exist inside the list." Really? Check whether an infinity of complex numbers ("all complex numbers") are in the list?? $\endgroup$ – David G. Stork Dec 19 '17 at 21:40
6
$\begingroup$
SeedRandom[1]
n = 10000;
ss1 = Table[RandomComplex[], {n}];
ss2 = Conjugate[ss1];
ss = Join[{ss1, ss2}] // Flatten;

You can also (1) check if Complement[ss, Conjugate[ss]] is empty or (2) check if Sort[ss] == Sort[Conjugate[ss]]:

Count[MemberQ[ss, Conjugate[#]] & /@ ss, False] // AbsoluteTiming

{33.556, 0}

Complement[ss, Conjugate[ss]] == {} // AbsoluteTiming

{0.01559, True}

Sort[ss] == Sort[Conjugate[ss]] // AbsoluteTiming

{0., True}

With n = 80000 we get:

Sort[ss] == Sort[Conjugate[ss]] // AbsoluteTiming

{0.078646, True}

$\endgroup$
  • $\begingroup$ Wonderful, Thanks $\endgroup$ – qahtah Dec 19 '17 at 21:42
  • $\begingroup$ @qahtah, my pleasure.Thank you for the accept. $\endgroup$ – kglr Dec 19 '17 at 21:43

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.