... until the collector arrives ...

This "blog" is really just a scratchpad of mine. There is not much of general interest here. Most of the content is scribbled down "live" as I discover things I want to remember. I rarely go back to correct mistakes in older entries. You have been warned :)

2012-01-21

Mathematica: Sort vs. Infinity

In Mathematica, the expression:

Sort[{4, 3, 2, 1, -∞, ∞}]

returns:

{1, 2, 3, 4, -∞, ∞}

The behaviour is explainable, if unintuitive. Infinities are different types of mathematical objects than, say, integers. Sort is defined to sort objects into "canonical order". Apparently that order places infinities after integers. Despite this explanation, the behaviour is definitely a gotcha to watch out for.

The workaround is to specify Less as the ordering function for Sort (instead of the default, OrderedQ):

Sort[{4, 3, 2, 1, -∞, ∞}, Less]

Blog Archive