Skip to content

Instantly share code, notes, and snippets.

@stefanv
Last active December 22, 2015 03:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stefanv/6413742 to your computer and use it in GitHub Desktop.
Save stefanv/6413742 to your computer and use it in GitHub Desktop.
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