Sorting an array of Doubles with NaN in it

后端 未结 5 1979
深忆病人
深忆病人 2021-01-11 10:26

This is more of a \'Can you explain this\' type of question than it is anything else.

I came across a problem at work where we were using NaN values in a table, but

5条回答
  •  忘掉有多难
    2021-01-11 10:58

    Conceptually NaN is Not a Number, so comparing to a number makes no sense, hence:

    a < NaN = false for all a,
    a > NaN = false for all a and
    NaN != NaN (!)
    

    To solve this you need to write your own comparer that uses IsNaN to make NaNs smaller than (or larger than) all numbers, so that they will all appear at one end of the sort.

    Edit: Here's a sample of the Comparison version:

    class Program
    {
        private static int NaNComparison(double first, double second)
        {
            if (double.IsNaN(first))
            {
                if (double.IsNaN(second)) // Throws an argument exception if we don't handle both being NaN
                    return 0;
                else
                    return -1;
            }
            if (double.IsNaN(second))
                return 1;
    
            if (first == second)
                return 0;
            return first < second ? -1 : 1;
        }
    
        static void Main(string[] args)
        {
            var doubles = new[] { double.NaN, 2.0, 3.0, 1.0, double.NaN };
    
            Array.Sort(doubles, NaNComparison);
        }
    }
    

提交回复
热议问题