什么是未初始化数组,numpy.empty返回的值是什么?

What is an uninitialized array and what are the values returned by numpy.empty?

我只是想了解一下 np.empty(),我知道它会创建一个未初始化的数组,但我无法理解这意味着什么以及这些值的来源。欢迎任何帮助,提前致谢。

numpy.empty 功能与numpy.zeros 完全相同,但它不关心设置值,只是通过分配内存来设置容器来存储future元素。

因此,您看到的值是随机值,源自之前可能存在于内存中的任何值。

这就是为什么文档强调 如果您打算自己完全填充数组,您应该只使用 numpy.empty

Notes

empty, unlike zeros, does not set the array values to zero, and may therefore be marginally faster. On the other hand, it requires the user to manually set all the values in the array, and should be used with caution.

numpy 不是 Python 而是 C 代码的包装器。 numpy.empty returns 一个(包装)一个未初始化的 C 数组。你永远不应该尝试读取一个你以前没有写过的值,因为它可以是任何东西,包括在拥有它的系统上的陷阱值。它被 C 程序员称为 未定义行为(地狱的近亲)...