Sorting floating-point values, and NaN

Vladimir Panteleev vladimir at thecybershadow.net
Mon Nov 11 20:41:55 PST 2013


double[] arr = [1, 2, 3, double.nan, 1, 2];
assert(arr.isSorted);
arr.sort();

This code will fail with an assert error, but not the one on the 
second line. Rather, it will fail inside std.range, when sort 
calls assumeSorted, which checks elements in an order different 
than sort and isSorted.

Here's a case where the odd way NaN interacts with generic code 
messes things up in an ugly way.

This is concerning. It's very easy to overlook this while writing 
an application, and it can become a hidden vulnerability.

We can't fix the operators... but, perhaps, we could define a 
safe default comparison predicate (e.g. std.algorithm.less) for 
use with sorting and related tasks? Aside from bitwise 
comparison, is it even possible to efficiently compare 
floating-point values in a way suitable for sorting?


More information about the Digitalmars-d mailing list