125

I am working with numpy arrays of a range of data types (uint8, uint16, int16, etc.). I would like to be able to check whether a number can be represented within the limits of an array for a given datatype. I am imagining something that looks like:

>>> im.dtype
dtype('uint16')
>>> dtype_max(im.dtype)
65535
>>> dtype_min(im.dtype)
0

Does something like this exist? By the way, I feel like this has to have been asked before, but my search came up empty, and all of the "similar questions" appear to be unrelated.

Edit: Of course, now that I've asked, one of the "related" questions does have the answer. Oops.

2 Answers 2

181
min_value = np.iinfo(im.dtype).min
max_value = np.iinfo(im.dtype).max

docs:

  • np.iinfo (machine limits for integer types)
  • np.finfo (machine limits for floating point types)
Sign up to request clarification or add additional context in comments.

3 Comments

Is there a simple way to do this without knowing if the type is float or int (thus having to choose between iinfo and finfo) ? Currently I'm using a try/catch, it's a bit cumbersome
@gdelab Instead of using try/catch, you can also use issubclass(dtype, np.integer) and issubclass(dtype, np.floating) for branching and selecting either np.iinfo or np.finfo.
@leon-w with recent versions of numpy (as of 2025), you can do a test with np.issubdtype instead: np.iinfo(dtype).min if np.issubdtype(dtype, np.integer) else np.finfo(dtype).min
25

You're looking for numpy.iinfo for integer types. Documentation here.

There's also numpy.finfo for floating point types. Documentation here.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.