数组比较与numpy中的元素比较不匹配
Array comparison not matching elementwise comparison in numpy
我有一个 numpy 数组 arr
。这是一个numpy.ndarray
,大小是(5553110,)
,dtype=float32
。
当我这样做时:
(arr > np.pi )[3154950]
False
(arr[3154950] > np.pi )
True
为什么第一次比较就出错了?我该如何解决?
值:
arr[3154950]= 3.1415927
np.pi= 3.141592653589793
精度有问题吗?
问题是由于 np.float32
与 np.float64
的准确性有关。
使用np.float64
,你不会发现问题:
import numpy as np
arr = np.array([3.1415927], dtype=np.float64)
print((arr > np.pi)[0]) # True
print(arr[0] > np.pi) # True
正如@WarrenWeckesser 评论的那样:
It involves how numpy decides to cast the arguments of its operations.
Apparently, with arr > scalar
, the scalar is converted to the same
type as the array arr
, which in this case is np.float32
. On the other
hand, with something like arr > arr2
, with both arguments nonscalar
arrays, they will use a common data type. That's why (arr >
np.array([np.pi]))[3154950]
returns True
.
我有一个 numpy 数组 arr
。这是一个numpy.ndarray
,大小是(5553110,)
,dtype=float32
。
当我这样做时:
(arr > np.pi )[3154950]
False
(arr[3154950] > np.pi )
True
为什么第一次比较就出错了?我该如何解决?
值:
arr[3154950]= 3.1415927
np.pi= 3.141592653589793
精度有问题吗?
问题是由于 np.float32
与 np.float64
的准确性有关。
使用np.float64
,你不会发现问题:
import numpy as np
arr = np.array([3.1415927], dtype=np.float64)
print((arr > np.pi)[0]) # True
print(arr[0] > np.pi) # True
正如@WarrenWeckesser 评论的那样:
It involves how numpy decides to cast the arguments of its operations. Apparently, with
arr > scalar
, the scalar is converted to the same type as the arrayarr
, which in this case isnp.float32
. On the other hand, with something likearr > arr2
, with both arguments nonscalar arrays, they will use a common data type. That's why (arr > np.array([np.pi]))[3154950]
returnsTrue
.