【问题标题】:Numpy function type casting automatically or notNumpy 函数类型是否自动转换
【发布时间】:2022-01-01 20:16:15
【问题描述】:

考虑以下 numpy 代码

foo = np.array([255, 255], dtype=np.uint8)
foo_sum = foo.sum()

foo_square_v1 = foo**2
foo_square_v2 = np.square(foo)
foo_square_v3 = np.pow(foo, 2)

foo_sum 正确转换为 uint64 并返回 510 但是所有 3 个foo_square 都没有触发类型转换并且有溢出(!!!),返回[1,1]

知道我应该手动进行投射还是 numpy 是否自动为我进行投射的经验法则是什么?

我的系统: Python 3.x、X64 机器、Linux、numpy 1.20.3

【问题讨论】:

    标签: python numpy types


    【解决方案1】:

    您似乎希望 NumPy 检测溢出并提升 dtypes 作为响应。 NumPy 永远不会那样做。大多数 NumPy 功能将只使用与输入相同的 dtype,或者在有多个 dtype 时遵循default promotion rules

    numpy.sum 是不寻常的,但即使它的 dtype 规则也不是你想要的。为numpy.sum 引用docsa 是输入数组):

    默认使用 a 的 dtype,除非 a 的整数 dtype 的精度低于默认平台整数。在这种情况下,如果 a 是有符号的,则使用平台整数,而如果 a 是无符号的,则使用与平台整数精度相同的无符号整数。

    这里的“默认平台整数”是 Clong(不是 Cint)。如果 C long 是 32 位(尤其是在 Windows 上)并且您需要 64 位输出以避免溢出,您仍然需要手动指定 dtype。

    【讨论】:

      猜你喜欢
      • 2014-05-25
      • 1970-01-01
      • 2015-10-03
      • 1970-01-01
      • 2018-05-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-10
      相关资源
      最近更新 更多