对包含NaN的列表进行排序 [英] Sorting a list containing NaNs

查看:59
本文介绍了对包含NaN的列表进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个包含以下各项的浮点数列表:Infinity,-Infinity,其他随机十进制数和一个NaN.列表排序后,NaN应该在哪里?我正在使用冒泡排序(如果有帮助的话)

If I have a list of floating point numbers containing: Infinity, -Infinity, Other random decimal number and one NaN. Where should the NaN be after the list has been sorted?? I'm using bubble sort if that helps

推荐答案

要进行排序,您需要一致的顺序,这意味着,例如,为NaN制定排序规则.

In order to sort you need a consistent order, which means, for example, making an ordering rule for NaN.

幸运的是,该工作已经用Java完成. java.lang.Double Comparable ,并且其 compareTo 使用扩展的规则,包括"Double.NaN被该方法视为与自身相等.并大于所有其他double值(包括Double.POSITIVE_INFINITY)."

Fortunately, the work has already been done in Java. java.lang.Double is Comparable, and its compareTo uses extended rules including "Double.NaN is considered by this method to be equal to itself and greater than all other double values (including Double.POSITIVE_INFINITY)."

它也有一个 compare 方法,使用这些扩展规则而不是< = 等规则来比较两个双原语.

It also has a compare method that compares two double primitives using those extended rules, rather than the <= etc. rules.

如果您使用Java进行编程,则可以直接在您的排序中使用它.如果您使用的是 float 而不是 double ,请参见 java.lang.Float 中的相应方法.如果您正在使用另一种语言进行编程,则仍然可以从Java中读取和复制规则,并将其用于比较功能中.

If you are programming in Java you can use this directly in your sort. If you are using float rather than double, see the corresponding method in java.lang.Float. If you are programming in another language, you can still read and copy the rules from Java, and use them in your comparison function.

如果在排序中使用此代码,则应该期望 NaN 在排序列表的最后,在所有有限值和正无穷大之后.

If you use this in your sort you should expect NaN to be at the very end of the sorted list, after all finite values and positive infinity.

这篇关于对包含NaN的列表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆