Skip to main content
 首页 » 编程设计

python之在运行时在 numpy 中查找最大整数类型

2025年05月04日17三少

我想知道是否有一种方法可以找出最大值,例如支持特定的整数类型(或无符号整数、 float 或复数 - 任何“固定大小”类型)通过 numpy 在运行时。也就是说,假设我知道(从文档中)当前版本的numpy 中最大的无符号整数类型是np。 uint64 我有一行代码,例如:

y = np.uint64(x) 

我希望我的代码使用任何最大的,比方说,无符号整数类型在我的代码使用的 numpy 版本中可用。也就是说,我有兴趣用这样的东西替换上面的硬编码类型:

y = np.largest_uint_type(x) 

有这样的方法吗?

请您参考如下方法:

你可以使用np.sctypes:

>>> def largest_of_kind(kind): 
...     return max(np.sctypes[kind], key=lambda x: np.dtype(x).itemsize) 
...  
>>> largest_of_kind('int') 
<class 'numpy.int64'> 
>>> largest_of_kind('uint') 
<class 'numpy.uint64'> 
>>> largest_of_kind('float') 
<class 'numpy.float128'> 
>>> largest_of_kind('complex') 
<class 'numpy.complex256'>