代码:
import sys
import numpy as np
print(f"We are using Python {sys.version}", file=sys.stderr)
print(f"We are using numpy version {np.__version__}", file=sys.stderr) # 2.2.1
def find_non_numpy_floats(x: any) -> bool:
if not (isinstance(x, np.float64)):
print(f"Found non-numpy.float64: {x} of type {type(x)}", file=sys.stderr)
return False
else:
return True
w: np.ndarray = np.zeros((2, 2), dtype=np.float64)
np.vectorize(lambda x: find_non_numpy_floats(x))(w)
assert (np.all(np.vectorize(lambda x: isinstance(x, np.float64))(w))), "try to keep using the numpy floats"
我期望numpy.zeros会生成一个numpyfloat64
d,如果我正确理解的话,它与python
float
(IEEE 64位浮子与特定于Python的东西)不同吗?)
上述结果是:
We are using Python 3.13.1 (main, Dec 9 2024, 00:00:00) [GCC 14.2.1 20240912 (Red Hat 14.2.1-3)]
We are using numpy version 2.2.1
Found non-numpy.float64: 0.0 of type <class 'float'>
Found non-numpy.float64: 0.0 of type <class 'float'>
Found non-numpy.float64: 0.0 of type <class 'float'>
Found non-numpy.float64: 0.0 of type <class 'float'>
和断言错误。
为什么这是我该如何修复此问题(我应该要?)
numpy.vectorize
# Convert args to object arrays first
inputs = [asanyarray(a, dtype=object) for a in args]
将数组转换为对象dtype的数组:
numpy.float64
我不知道为什么。我能想到一些合理的原因,但没有什么明显的动力。
float64 dtype阵列不可能包含普通的python浮子。 float64 dtype的数组具有原始8字节浮点值的缓冲区,而不是python对象。如果您尝试访问单个元素,它们甚至都不是thumpy的实例。