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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…