Why is this list returned unchanged by Sort?



While this list is returned reversed?



Mathematica MacOS

  • $\begingroup$ also see (2729) $\endgroup$
    – WReach
    Dec 3 '16 at 20:41

The Wolfram Documentation says:

Sort by default orders integers, rational, and approximate real numbers by their numerical values.

It also says:

Sort usually orders expressions by putting shorter ones first, and then comparing parts in a depth‐first manner.

The phrase -Pi/2 is an expression, so this second definition is applying. i.e. if we convert each expression to 'atomic'/numerical values first...

Sort[{0 // N, -Pi/2 // N}]
> {-1.5708, 0.}

... then it behaves as expected. You can force it to sort by numerical value by explicitly specifying the method used to compare entries for Sorting:

Sort[{0, -Pi/2}, Less]
> {-Pi/2, 0}
  • 2
    $\begingroup$ This is no bug; see Sort bug in Mathematica 10?. $\endgroup$
    – corey979
    Dec 3 '16 at 20:04
  • $\begingroup$ @corey979 - Thanks, edited my answer accordingly. $\endgroup$
    – Myridium
    Dec 3 '16 at 20:19
  • 1
    $\begingroup$ Thanks to all who replied. I don't personally think Sort ought to treat -Pi/2 as anything but a number by default, but now that I understand what is going on I will just always explicitly specify a sorting method such as Less. $\endgroup$ Dec 6 '16 at 10:56
  • $\begingroup$ SortBy[list, N] can be used as well. $\endgroup$
    – J. M.'s torpor
    Dec 10 '16 at 2:51

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