Skip to content

Instantly share code, notes, and snippets.

@stefanv
Last active Dec 22, 2015
Embed
What would you like to do?
Find the minimum dtype required to represent the elements of an integer array.
import numpy as np
dtype_range = [(np.bool, (False, True)),
(np.bool8, (False, True)),
(np.uint8, (0, 255)),
(np.int8, (-128, 127)),
(np.uint16, (0, 65535)),
(np.int16, (-32768, 32767)),
(np.uint32, (0, 4294967295)),
(np.int32, (-2147483648, 2147483647)),
(np.uint64, (0, 18446744073709551615)),
(np.int64, (-9223372036854775808, 9223372036854775807))]
def min_typecode(a):
"""Find the minimum type code needed to represent the integers in `a`.
"""
a = np.asarray(a)
if not np.issubdtype(a.dtype, np.integer):
raise ValueError("Can only handle integer arrays.")
a_min, a_max = a.min(), a.max()
for t, (t_min, t_max) in dtype_range:
if np.all(a_min >= t_min) and np.all(a_max <= t_max):
return t
else:
raise ValueError("Could not find suitable dtype.")
if __name__ == "__main__":
print "[0, -1] -> ", min_typecode([0, -1])
print "[0, 256] -> ", min_typecode([0, 256])
print "[-1, 256] -> ", min_typecode([-1, 256])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment