这是this个问题的后续.

When we use a numpy array with a specific type, it preserves its type following numeric operations.
For example adding 1 to a uint32 array will wrap up the value to 0 if needed (when the array contained the max uint32 value) and keep the array of type uint32:

import numpy
a = numpy.array([4294967295], dtype='uint32')
a += 1   # will wrap to 0
print(a)
print(a.dtype)

输出:

uint32
[0]
uint32

对于具有相同类型的数组scalar,此行为不成立:

import numpy
a = numpy.uint32(4294967295)
print(a.dtype)
a += 1   # will NOT wrap to 0, and change the scalar type
print(a)
print(a.dtype)

输出:

uint32
4294967296
int64

但根据前array scalars documentation名:

使用数组标量的主要优点是它们保留数组类型

...

因此,数组标量的使用确保了identical behaviour between arrays and scalars,不管值是否在数组内部.

(emphasys is mine)

My question:
Why do I observe the above different behavior between arrays and scalars despite the explicit documentation that states they should behave identically ?

推荐答案

正如 comments 中提到的:是的,这个文档充其量是不精确的.我认为它指的是同一类型标量之间的行为:

import numpy
a = numpy.uint32(4294967295)
print(a.dtype)  # uint32
a += np.uint32(1)   # WILL wrap to 0 with warning
print(a)  # 0
print(a.dtype)  # uint32

然而,示例的行为将由于NumPy 2.0中的NEP 50而改变.因此,尽管旧的行为令人沮丧,但除了等待之外没有什么可做的,除非您想提出一个关于文档更改的向后移植问题.如Migration Guide所示.

它最大的向后兼容性变化是,它意味着标量的精度现在得到一致的保留…… np.float32(3) + 3.现在返回float32,而以前它返回float64.

我已经确认,在您的示例中,类型按照预期保留.

import numpy
a = numpy.uint32(4294967295)
print(a.dtype)  # uint32
a += 1  # will wrap to 0 
print(a)  # 0
print(a.dtype)  # uint32
numpy.__version__  # '2.1.0.dev0+git20240318.6059db1'

第二个NumPy 2.0发布候选版本已经发布,如果你想try 一下: https://mail.python.org/archives/list/numpy-discussion@python.org/thread/EGXPH26NYW3YSOFHKPIW2WUH5IK2DC6J/

Python相关问答推荐

如何使用matplotlib在Python中使用规范化数据和原始t测试值创建组合热图?

ModuleNotFound错误:没有名为flags.State的模块; flags不是包

沿着数组中的轴计算真实条目

输出中带有南的亚麻神经网络

在Mac上安装ipython

如何使用scipy的curve_fit与约束,其中拟合的曲线总是在观测值之下?

索引到 torch 张量,沿轴具有可变长度索引

不能使用Gekko方程'

如何使regex代码只适用于空的目标单元格

python—telegraph—bot send_voice发送空文件

Flask运行时无法在Python中打印到控制台

如何将一组组合框重置回无 Select tkinter?

根据Pandas中带条件的两个列的值创建新列

高效生成累积式三角矩阵

如何在SQLAlchemy + Alembic中定义一个"Index()",在基表中的列上

对于标准的原始类型注释,从键入`和`从www.example.com `?

如何在Quarto中的标题页之前创建序言页

通过对列的其余部分进行采样,在Polars DataFrame中填充_null`?

如何将django url参数传递给模板&S url方法?

了解如何让库认识到我具有所需的依赖项