You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何numpy数组与≥10**20的数相乘时dtype自动变为object?

NumPy数组与大数值相乘的 dtype 异常问题

先定义一个基础的float64类型NumPy数组:

import numpy as np

a = np.array([1.])
print(a.dtype)  # 输出:float64

当该数组与大于等于10²⁰的数值相乘时,会出现 dtype 异常变化或报错:

print((a*10**19).dtype)  # 输出:float64
print((a*10**20).dtype)  # 输出:object

a *= 10**20  # 抛出 TypeError: ufunc 'multiply' output (typecode 'O') 
#             could not be coerced to provided output parameter (typecode 'd') 
#             according to the casting rule ''same_kind''

a *= 10.**20  # 抛出 numpy.core._exceptions._UFuncOutputCastingError: 
#             Cannot cast ufunc 'multiply' output from dtype('float64') to 
#             dtype('int32') with casting rule 'same_kind'

但以下两种操作不会触发该问题:

  • 逐元素直接相乘:
a[0] *= 10**20  
print(a, a.dtype)  # 输出:[1.e+20] float64
  • 将大数值显式转换为float(或int)后再执行乘法:
a *= float(10**20)  
print(a, a.dtype)  # 输出:[1.e+20] float64

另外,在原生Python环境中执行相同乘法操作不会有任何异常:

b = 1.
print(type(b), type(10**20), type(10.**20))  # 输出:<class 'float'> <class 'int'> <class 'float'>

b *= 10**20
print(type(b))  # 输出:<class 'float'>

内容的提问来源于stack exchange,提问作者mapf

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 20:05:26