如何找到最小numpy dtype来存储最大整数值?

问题描述

我需要创建一个非常大的numpy数组,该数组将容纳非负整数值。我预先知道最大的整数是什么,所以我想尝试使用最小的数据类型。到目前为止,我有以下内容:

>>> import numpy as np
>>> def minimal_type(max_val,types=[np.uint8,np.uint16,np.uint32,np.uint64]):
    ''' finds the minimal data type needed to correctly store the given max_val
        returns None if none of the provided types are sufficient
    '''
    for t in types:
        if max_val <= np.iinfo(t).max:
            return t
    return None

>>> print(minimal_type(42))
<class 'numpy.uint8'>
>>> print(minimal_type(255))
<class 'numpy.uint8'>
>>> print(minimal_type(256))
<class 'numpy.uint16'>
>>> print(minimal_type(4200000000))
<class 'numpy.uint32'>
>>> 

是否有内置numpy的方式来实现此功能?

解决方法

它是numpy.min_scalar_type。文档中的示例:

>>> np.min_scalar_type(10)
dtype('uint8')
>>> np.min_scalar_type(-260)
dtype('int16')
>>> np.min_scalar_type(3.1)
dtype('float16')
>>> np.min_scalar_type(1e50)
dtype('float64')
>>> np.min_scalar_type(np.arange(4,dtype='f8'))
dtype('float64')

您可能对float的行为不感兴趣,但是无论如何我都会将其包含在其他遇到此问题的其他人中,尤其是因为使用float16和缺少float-> int降级可能令人惊讶。 / p>

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...