4
$\begingroup$

I have the following list oflists. I am using SortBy function this in the increasing order of last element of each sublists. However, it seems to yield a wrong answer. Can Someone help me understand the result.

list = {{1, 2, 1/2}, {5, 3, 1/10 (5 - Sqrt[15])}, {3, 1, 1/10 (5 + Sqrt[15])}}
list = SortBy[list, Last]

The output that I am getting is

{{1, 2, 1/2}, {5, 3, 1/10 (5 - Sqrt[15])}, {3, 1, 1/10 (5 + Sqrt[15])}}

Why is this so?

$\endgroup$
  • $\begingroup$ Welcome to Mathematica.SE! I suggest the following: 1) As you receive help, try to give it too, by answering questions in your area of expertise. 2) Take the tour! 3) When you see good questions and answers, vote them up by clicking the gray triangles, because the credibility of the system is based on the reputation gained by users sharing their knowledge. Also, please remember to accept the answer, if any, that solves your problem, by clicking the checkmark sign! $\endgroup$ – Michael E2 Aug 10 '16 at 1:51
6
$\begingroup$

Sort and related functions sort the elements of list into canonical order. Canonical order is only numeric order if the elements are numeric rather than symbolic. You want to sort by the numerical values.

list = {{1, 2, 1/2}, {5, 3, 1/10 (5 - Sqrt[15])}, {3, 1, 
    1/10 (5 + Sqrt[15])}};

SortBy[list, N[Last[#]] &]

(*  {{5, 3, (1/10)*(5 - Sqrt[15])}, 
   {1, 2, 1/2}, {3, 1, 
     (1/10)*(5 + Sqrt[15])}}  *)

Or more succinctly using Composition

SortBy[list, N@*Last]

(*  {{5, 3, (1/10)*(5 - Sqrt[15])}, 
   {1, 2, 1/2}, {3, 1, 
     (1/10)*(5 + Sqrt[15])}}  *)

Check order

% // N

(*  {{5., 3., 0.112702}, {1., 2., 0.5}, {3., 1., 0.887298}}  *)
$\endgroup$
  • $\begingroup$ when I looked at possible issues in Sort and Sortby, I saw nothing about this. Do you know where it is mentioned? $\endgroup$ – Nasser Aug 10 '16 at 2:39
  • $\begingroup$ @Nasser - The first line of documentation for Sort states "Sort[list] sorts the elements of list into canonical order." The first line under Details states "Sort by default orders integers, rational, and approximate real numbers by their numerical values." (Note the absence of numeric expressions from this list.) The first example under Possible Issues states "Numeric expressions are sorted by structure as well as numerical value" and then gives an example of the canonical order not being numeric order. $\endgroup$ – Bob Hanlon Aug 10 '16 at 2:59

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.