Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Allow overflow for numpy types

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.

like image 613
fabian789 Avatar asked Oct 25 '25 10:10

fabian789


1 Answers

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
like image 87
user545424 Avatar answered Oct 27 '25 00:10

user545424



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!