为什么"NaN"被认为“较小"?比numpy中的-np.inf更多? [英] Why is `NaN` considered "smaller" than `-np.inf` in numpy?

查看:137
本文介绍了为什么"NaN"被认为“较小"?比numpy中的-np.inf更多?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在涉及np.minnp.argmin的任何比较中,认为NaN小于-np.inf的原因是什么?

What is the reason that NaN's are considered less than -np.inf in any comparisons involving np.min or np.argmin?

import numpy as np
In [73]: m = np.array([np.nan, 1., 0., -np.inf])
In [74]: n = np.array([-np.inf, 1., 0., np.nan])

# Huh??
In [75]: np.min(m)
Out[75]: nan
In [76]: np.min(n)
Out[76]: nan

# Same for np.argmin
In [77]: np.argmin(m)
Out[77]: 0
In [78]: np.argmin(n)
Out[78]: 3

# Its all false!
In [79]: np.nan < -np.inf
Out[79]: False

In [80]: np.nan > -np.inf
Out[80]: False

# OK, that seems to fix it, but its not necessarily elegant
In [81]: np.nanmin(m)
Out[81]: -inf

In [82]: np.nanargmin(m)
Out[82]: 3

我猜想它可能与返回FalseNaN值进行任何比较时都有副作用,但是当您碰巧"有时在结果中以NaN值结束时,这种恕我直言会带来一些相当烦人的效果.您的数组. np.nanminnp.nanargmin的使用感觉就像是一种快速修复程序,以某种方式装订在现有行为的基础上.

I would guess that its probably a side effect of any comparisons with NaN values returning False, however this imho leads to some rather annoying effects when you "happen" to sometimes end up with a NaN value in your array. The usage of np.nanmin or np.nanargmin some feels like a quickfix that was somehow stapled on top of the existing behaviour.

除了 docs :传播 NaN值,也就是说,如果至少一项是NaN,则相应的最小值也将是NaN.要忽略NaN值(MATLAB行为),请使用nanmin. ,我还没有找到任何能解释这种行为背后原因的东西.这是想要的还是NaN值的特定内部表示的副作用?为什么?

Apart from that note in the docs: "NaN values are propagated, that is if at least one item is NaN, the corresponding min value will be NaN as well. To ignore NaN values (MATLAB behavior), please use nanmin., I haven't found anything that explains the rationale behind that behaviour. Is this wanted or a side effect of a particular internal representation of NaN values? And why?

推荐答案

正如@Dunno在评论中提到的,将NaN与数字进行比较并没有太大的意义,因此这种行为可能是可以的. IEEE 754标准对此进行了说明,以将NaN与数字进行比较:

As @Dunno mentioned in a comment, it does not give much meaning to compare a NaN with a number, so this behaviour is probably ok. The IEEE 754 standard says this about comparing NaNs with numbers:

四个互斥关系是可能的:小于,相等,大于和无序.最后一种情况 当至少一个操作数为NaN时出现.每个NaN都应将无序与所有事物进行比较,包括 本身

Four mutually exclusive relations are possible: less than, equal, greater than, and unordered. The last case arises when at least one operand is NaN. Every NaN shall compare unordered with everything, including itself

根据标准,这是

# Its all false!
In [79]: np.nan < -np.inf
Out[79]: False

将导致无序"结果,因此它不属于关系小于"是不正确的.

would result in an "unordered" result, so it is not true that it is belongs to the relation "less than".

这篇关于为什么"NaN"被认为“较小"?比numpy中的-np.inf更多?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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