为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

沧海一幻觉 2023-05-16 14:24:49
我需要创建一个非常大的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内置的方法来实现这个功能?
查看完整描述

1 回答

?
白猪掌柜的

TA贡献1893条经验 获得超10个赞

它是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')

您可能对浮点数的行为不感兴趣,但无论如何我都会为遇到这个问题的其他人包括它,特别是因为使用 float16 并且缺少 float->int 降级可能会令人惊讶。


查看完整回答
反对 回复 2023-05-16
  • 1 回答
  • 0 关注
  • 57 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信