简体   繁体   English

数组比较不匹配numpy中的元素比较

[英]Array comparison not matching elementwise comparison in numpy

I have a numpy array arr . 我有一个numpy数组arr It's a numpy.ndarray , size is (5553110,) , dtype=float32 . 这是一个numpy.ndarray ,大小是(5553110,)(5553110,) dtype=float32

When I do: 当我做:

(arr > np.pi )[3154950]
False
(arr[3154950] > np.pi )
True

Why is the first comparison getting it wrong? 为什么第一次比较错了? And how can I fix it? 我该如何解决?

The values: 价值:

arr[3154950]= 3.1415927
np.pi= 3.141592653589793

Is the problem with precision? 问题是精确的吗?

The problem is due to accuracy of np.float32 vs np.float64 . 问题是由于np.float32np.float64准确性。

Use np.float64 and you will not see a problem: 使用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

As @WarrenWeckesser comments: 正如@WarrenWeckesser评论:

It involves how numpy decides to cast the arguments of its operations. 它涉及numpy如何决定投射其操作的参数。 Apparently, with arr > scalar , the scalar is converted to the same type as the array arr , which in this case is np.float32 . 显然,使用arr > scalar ,标量将转换为与数组arr相同的类型,在本例中为np.float32 On the other hand, with something like arr > arr2 , with both arguments nonscalar arrays, they will use a common data type. 另一方面,使用arr > arr2 ,两个参数都是非标量数组,它们将使用通用数据类型。 That's why ( arr > np.array([np.pi]))[3154950] returns True . 这就是为什么( arr > np.array([np.pi]))[3154950]返回True

Related github issue 相关的github问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM