I need to create a very large numpy array that will hold non-negative integer values. I know in advance what the largest integer will be, so I want to try to use the smallest datatype possible. So far I have the following:
>>> 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'>
>>>
Is there a numpy builtin way to achieve this functionality?