Message Boards Message Boards

2
|
3731 Views
|
2 Replies
|
10 Total Likes
View groups...
Share
Share this post:

Why SortBy does not sort as expected with Sin, Cos, Exp functions?

Posted 8 years ago

I am trying to write functions for SortBy. Working example is

SortBy[{1, 2, 3, 4, 5, 6, 7, 8, 9}, (# - 4)^2 &]

The output is

{4, 3, 5, 2, 6, 1, 7, 8, 9}

However, if I try using Sin, Cos or Exp, the sorting fails. Examples are

SortBy[{1, 2, 3, 4, 5, 6, 7, 8, 9}, Sin[#] &]
SortBy[{1, 2, 3, 4, 5, 6, 7, 8, 9}, Cos[#] &]
SortBy[{1, 2, 3, 4, 5, 6, 7, 8, 9}, -Exp[#] &]

All return unsorted list

{1, 2, 3, 4, 5, 6, 7, 8, 9}

I would like to know what is wrong with using Sin, Cos or Exp in sorting.

POSTED BY: Danko Georgiev
2 Replies

As Neil said, you need a numerical value. The reason why: Sort sorts based on the function Order (or equivalently OrderedQ), which gives the canonical order of two expressions (not the numerical!).

Order[Sin[3], Sin[4]]
Order[N@Sin[3], N@Sin[4]]

The first gives 1 (meaning they are in order) the second gives -1 (meaning they are not in order)

This is because they Sin[3] and Sin[4] are left unevaluated in Mathematica. Written like that they are in order (3<4). So in order to have compare the numerical approximations of Sin[1] rather than "Sin[1]" you need to convert it using N (either before or in the pure function):

SortBy[{1, 2, 3, 4, 5, 6, 7, 8, 9}, N@*Sin]
SortBy[{1, 2, 3, 4, 5, 6, 7, 8, 9}, N@*Cos]
SortBy[{1, 2, 3, 4, 5, 6, 7, 8, 9}, N@*Minus@*Exp]

These problems will become easier in a future version of the Wolfram language as a new function will be introduced that I can't talk about yet... keep your eyes open for this functionality in future versions...

POSTED BY: Sander Huisman

Danko,

The sorting function must be numeric, not symbolic. Sin[1] returns Sin[1], etc. Do this instead:

SortBy[{1, 2, 3, 4, 5, 6, 7, 8, 9}, N[Sin[#]] &]

or

SortBy[N[{1, 2, 3, 4, 5, 6, 7, 8, 9}], Sin[#] &]

Using the first version, your answer is:

{5, 4, 6, 3, 9, 7, 1, 2, 8}

Regards,

Neil

POSTED BY: Neil Singer
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract