Skip to content

Clarify floating-point sort order for ascending and descending sort #288

Closed

Description

@kgryte

Currently, the specification does not indicate the behavior for sorting the IEEE 754 floating-point values: NaN, -0, and +0.

In NumPy, NaN values are sorted to the end and signed zeros are not sorted:

In [1]: np.sort([2.0, 0.0, 1.0, -0.0, np.nan, np.nan, 3.0])                                                                                   
Out[1]: array([ 0., -0.,  1.,  2.,  3., nan, nan])

When sorting lists in Python, NaN values are left in place and signed zeros are not sorted:

In [1]: list = [2.0,0.0,1.0,-0.0,float('nan'),float('nan'),3.0,-1.0];                                                                         

In [2]: list.sort()                                                                                                                           

In [3]: list                                                                                                                                  
Out[3]: [-1.0, 0.0, -0.0, 1.0, 2.0, nan, nan, 3.0]

Other languages have made different design decisions. E.g., Julia sorts signed zeros and places NaN values at the end.

julia> sort([2.0,1.0,0.0,-0.0,NaN,NaN,3.0,-1.0])
8-element Array{Float64,1}:
  -1.0
  -0.0
   0.0
   1.0
   2.0
   3.0
 NaN  
 NaN

IMO, we should clarify the sort order for ascending and descending sort. Preferably,

  • sorting signed zeros
  • sorting NaN values to the end when sorting in ascending order and to the beginning when sorting in descending order

Activity

  1. added
    API changeChanges to existing functions or objects in the API.
    on Oct 21, 2021
  2. added this to the v2021 milestone on Oct 21, 2021
  3. kgryte commented on Oct 21, 2021

    @kgryte
    ContributorAuthor

    By specifying sort order for floating-point values, this has implications for unique (see gh-249), as sorting NaN values to the ends affords relatively straightforward workarounds for handling multiple returned NaNs as discussed in the referenced issue.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    API changeChanges to existing functions or objects in the API.

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions