1
$\begingroup$

This question already has an answer here:

Why is this list returned unchanged by Sort?

Sort[{0,-Pi/2}]

{0,-Pi/2}

While this list is returned reversed?

Sort[{0,-1}]

{-1,0}

Mathematica 11.0.0.0 MacOS

$\endgroup$

marked as duplicate by J. M. will be back soon Dec 10 '16 at 2:52

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

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

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}
$\endgroup$
  • 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$ – Ralph Dratman Dec 6 '16 at 10:56
  • $\begingroup$ SortBy[list, N] can be used as well. $\endgroup$ – J. M. will be back soon Dec 10 '16 at 2:51

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