def minimum_dtype(x, dtype=np.bool_):
"""returns the "most basic" dtype which represents `x` properly, which
provides at least the same value range as the specified dtype."""
def check_type(x, dtype):
try:
converted = dtype.type(x)
except (ValueError, OverflowError):
return False
# False if some overflow has happened
return converted == x or math.isnan(x)
def type_loop(x, dtype, dtype_dict, default=None):
while True:
try:
dtype = np.dtype(dtype_dict[dtype.name])
if check_type(x, dtype):
return np.dtype(dtype)
except KeyError:
if default is not None:
return np.dtype(default)
raise ValueError("Can not determine dtype of %r" % x)
dtype = np.dtype(dtype)
if check_type(x, dtype):
return dtype
if np.issubdtype(dtype, np.inexact):
return type_loop(x, dtype, _next_float_dtype)
else:
return type_loop(x, dtype, _next_int_dtype, default=np.float32)
评论列表
文章目录