4

I'm trying to get the "normal" overflow/underflow behavior of C-type languages in Python. To my surprise, a RuntimeWarning is raised when I'm trying to get this behavior. Example:

np.uint8(255) + np.uint8(1)
>>> RuntimeWarning: overflow encountered in ubyte_scalars

Is there any way to simulate the desired behavior, i.e., that 255+1 gives 0?

I tried the docs but cannot find this behavior documented.

1 Answer 1

3

I believe numpy does give you the correct behavior.

In [1]: np.uint8(255) + np.uint8(1)
/usr/bin/ipython:1: RuntimeWarning: overflow encountered in ubyte_scalars
  #!/usr/bin/python2
Out[1]: 0

You can suppress the warning by running:

In [1]: np.seterr(over='ignore')
Out[1]: {'divide': 'warn', 'invalid': 'warn', 'over': 'warn', 'under': 'ignore'}

In [2]: np.uint8(255) + np.uint8(1)
Out[2]: 0
Sign up to request clarification or add additional context in comments.

3 Comments

I see. So I guess these uint8 are by no means native? Is there any way to get fast uint8 semantics without resorting to a lower-level language?
What do you mean by native? I think internally they are indeed represented as a uint8 same as in C, there is just some extra error checking going on.
It appears that this check is only done for unsigned integers when adding scalars too since it would be too expensive to do for arrays. Have a look here: github.com/numpy/numpy/issues/8987.

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.