Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
243 views
in Technique[技术] by (71.8m points)

python - Numpy No Overflow Exception on uint16 Addition

I want to add noise to my uint16 signal, but I want to avoid overflows in case some signal values are zero:

np.seterr(all='raise')
noise = np.random.normal(0,2,9*9).reshape(9,9)
noise = np.around(noise,out=noise)
noise = noise.astype(np.uint16,copy=True)
signal = np.zeros((9,9), dtype=np.uint16)
try:
    signal += noise
except FloatingPointError:
    print("Overflow Detected")
    # Handle overflows
print(test)

Unfortunately there is no exception raised. The example from the doc works.

>>> np.int16(32000) * np.int16(3)
---------------------------------------------------------------------------
FloatingPointError                        Traceback (most recent call last)
<ipython-input-84-5e468485740e> in <module>
----> 1 np.int16(32000) * np.int16(3)

Is there a way to enable an exception for uint16 addition?

Or is there an efficient way to check for overflows which does not involve going through the array element-by-eliment?

question from:https://stackoverflow.com/questions/65890972/numpy-no-overflow-exception-on-uint16-addition

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Numpy supports broadcasting comparison operators. Thus, the problem can be solved by checking the result for illegal values. In my case the signal is actually 12-bit, so any values above 2**12-1 must have come from an overflow.

noise = np.random.normal(0,2,9*9).reshape(9,9)
noise = np.around(noise,out=noise)
noise = noise.astype(np.uint16,copy=True)
test = np.zeros((9,9), dtype=np.uint16)
test += noise
check = test > 2**12-1
if check.any():
    print("Overflow detected")

If you have actual 16-bit values, the arithmetic operation (e.g. addition) can be performed in a 32-bit array; You can then check for illegal values in the same fashion.

You can also handle the overflow immediately with np.where():

np.where(a > OVERFLOW_BOUNDARY, f(a), a)

Note that you probably want to differentiate between an overflow and an underflow in your handler function.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...