Skip to main content

sorting - SortBy misbehaving?


It maybe a stupid thing in the end but I'm stuck a couple of hours now.


I have a list of 2 points on the plane and I want to get the one with the biggest second coordinate. I thought I knew how SortBy operates. For example


SortBy[{{a, 1/2 (2 + Sqrt[2])}, {b, 1/2 (3 + Sqrt[2])}, {c, 1/2 (1 + Sqrt[2])}}, Function[{x}, x[[2]]]]

gives as expected the answer


{{c, 1/2 (1 + Sqrt[2])}, {a, 1/2 (2 + Sqrt[2])}, {b, 1/2 (3 + Sqrt[2])}}

and



SortBy[{{a, 1/2 (2 + Sqrt[2])}, {b, 1/2 (3 + Sqrt[2])}, {c, 1/2 (1 + Sqrt[2])}}, Function[{x}, -x[[2]]]]

gives as an answer


{{b, 1/2 (3 + Sqrt[2])}, {a, 1/2 (2 + Sqrt[2])}, {c, 1/2 (1 + Sqrt[2])}}

which is perfectly fine.


My list is


{{4/13 (-9 - Sqrt[3]), 6/13 (4 - Sqrt[3])}, {4/13 (-9 + Sqrt[3]), 6/13 (4 + Sqrt[3])}}

and the command



SortBy[{{4/13 (-9 - Sqrt[3]), 6/13 (4 - Sqrt[3])}, {4/13 (-9 + Sqrt[3]), 6/13 (4 + Sqrt[3])}}, Function[{x}, x[[2]]]]

gives the answer


{{4/13 (-9 - Sqrt[3]), 6/13 (4 - Sqrt[3])}, {4/13 (-9 + Sqrt[3]), 6/13 (4 + Sqrt[3])}}

which is the same as the answer I get from


SortBy[{{4/13 (-9 - Sqrt[3]), 6/13 (4 - Sqrt[3])}, {4/13 (-9 + Sqrt[3]), 6/13 (4 + Sqrt[3])}}, Function[{x}, -x[[2]]]]

Can someone explain to me what's going on? This drives me crazy.



Answer




I don't know exactly why Mathematica is giving a wrong result, but here's a workaround:


SortBy[{{4/13 (-9 - Sqrt[3]), 6/13 (4 - Sqrt[3])}, {4/13 (-9 + Sqrt[3]), 6/13 (4 + Sqrt[3])}}, 
-N @ #[[2]] &]

Mathematica graphics


That is, force Mathematica to sort by their numerical value.


OR you can use Sort instead:


Sort[{{4/13 (-9 - Sqrt[3]), 6/13 (4 - Sqrt[3])}, {4/13 (-9 + Sqrt[3]),
6/13 (4 + Sqrt[3])}}, #1[[2]] > #2[[2]] &]


Which gives the same result.


Comments