min/max of collections containing NaN (handling incomparability in ordering)

后端 未结 4 2049
别跟我提以往
别跟我提以往 2021-02-14 00:38

I just ran into a nasty bug as a result of the following behavior:

scala> List(1.0, 2.0, 3.0, Double.NaN).min
res1: Double = NaN

scala> List(1.0, 2.0, 3.0         


        
4条回答
  •  难免孤独
    2021-02-14 01:11

    For

    val a = List(1.0, 2.0, 3.0, Double.NaN)
    

    sort it,

    a.sortWith {_ >_ }
    res: List[Double] = List(3.0, 2.0, 1.0, NaN)
    

    and so NaN values are relegated, thus for max,

    a.sortWith {_ >_ }.head
    res: Double = 3.0
    

    Likewise

    a.sortWith {_ < _ }
    res: List[Double] = List(1.0, 2.0, 3.0, NaN)
    

    and so for min,

    a.sortWith {_ < _ }.head
    res: Double = 1.0
    

提交回复
热议问题