How can one sort a list of complex numbers in increasing order with respect to their imaginary part in Maple?

1.3k Views Asked by At

I am a beginner at Maple and am attempting to use the sort function to order a list of complex numbers according to their imaginary part, however I can find no function options that help. Will I have to use a loop?

1

There are 1 best solutions below

1
On

Maple's sort command allows you to use a custom procedure as the predicate to compare two elements.

For example, to sort a list of numeric entries according by their imaginary component:

L:=[ 3+4*I, 6-I, -3, 2, 0.4*I ];

                  L := [3 + 4 I, 6 - I, -3, 2, 0.4 I]

sort( L, (a,b) -> Im(a)<Im(b) );

                    [6 - I, 2, -3, 0.4 I, 3 + 4 I]

You could also use a comparison procedure which compared the real components, in the case that the imaginary components were equal.

p := proc(a,b)
  if Im(a) < Im(b) then
    true;
  elif Im(a) = Im(b) then
    if Re(a) < Re(b) then
      true;
    else
      false;
    end if;
  else
    false;
  end if;
end proc:

L:=[ 3+4*I, 6-I, -3, 2, 0.4*I, -3+4*I, -6-I ];

sort( L, p );

           [-6 - I, 6 - I, -3, 2, 0.4 I, -3 + 4 I, 3 + 4 I]

The comparison procedures above utilizes < under evalb for its boolean evaluation. That combination handles elements of type numeric, but does not handle elements which are of type realcons but not of type numeric.

For example, the following does not return true or false, since sqrt(2) is not of type numeric. It simply returns unevaluated.

evalb( sqrt(2) < 5 );

                                1/2
                               2    < 5

By utilizing the is command we can strengthen the test to also handle such quantities of type realcons. Eg,

is( sqrt(2) < 5 );

                                 true

This reasoning carries over to sort as well,

L := [ 3+4*I, 6-I, sqrt(2)*I, -3, 2, 0.4*I ];

                                     1/2
              L := [3 + 4 I, 6 - I, 2    I, -3, 2, 0.4 I]

sort( L, (a,b) -> Im(a)<Im(b) );               
 Error, sort: comparison function argument, (a, b) -> Im(a) < Im(b),
 must be a function that always returns true or false

sort( L, (a,b) -> is(Im(a)<Im(b)) );

                                       1/2
                [6 - I, 2, -3, 0.4 I, 2    I, 3 + 4 I]