[英]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:我想为我的 uint16 信号添加噪声,但我想避免溢出,以防某些信号值为零:
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?有没有办法为 uint16 添加启用异常?
Or is there an efficient way to check for overflows which does not involve going through the array element-by-eliment?或者是否有一种有效的方法来检查不涉及逐个元素遍历数组的溢出?
Numpy supports broadcasting comparison operators. Numpy 支持广播比较运算符。 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.在我的情况下,信号实际上是 12 位的,所以任何高于
2**12-1
的值都必须来自溢出。
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 (eg addition) can be performed in a 32-bit array;如果您有实际的 16 位值,则可以在 32 位数组中执行算术运算(例如加法); You can then check for illegal values in the same fashion.
然后,您可以以相同的方式检查非法值。
You can also handle the overflow immediately with np.where() :您还可以使用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.请注意,您可能希望在处理程序 function 中区分上溢和下溢。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.