How to recognize overflow bugs in Matlab?
I spent part of yesterday and today tracking down a bug in some Matlab code. I had thought my problem was indexing (with many structures that I didn't define and am still getting used to), but it turned out to be an overflow bug. I missed this for a very specific reason:
>> uint8(2) - uint8(1)
ans =
1
>> uint8(2) - uint8(2)
ans =
0
>> uint8(2) - uint8(3)
ans =
0
I would 开发者_运维技巧have expected the last one to be something like -1
(or 255
). In the middle of a big vector, the erroneous 0
s were difficult to detect, but a 255
would have stood out easily.
Any tips on how to detect these problems easily in the future? (Ideally, I'd like to turn off the overflow checking to make it work like C.) Changing to double
works, of course, but if I don't realize it's a uint8
to begin with, that doesn't help.
You can start by turning on integer warnings:
intwarning('on')
This will give you a warning when integer arithmetic overflows.
Beware though, as outlined here, this does slow down integer arithmetic so only use this during debug.
Starting with release R2010b and later, the function INTWARNING has been removed, along with these warning messages for integer math and conversion:
MATLAB:intConvertNaN
MATLAB:intConvertNonIntVal
MATLAB:intConvertOverflow
MATLAB:intMathOverflow
So using INTWARNING is no longer a viable option for determining when integer overflows occur. An alternative is to use the CLASS function to test the class of your data and recast it accordingly before performing the operation. Here's an example:
if strcmp(class(data),'uint8') %# Check if data is a uint8
data = double(data); %# Convert data to a double
end
You could also use the ISA function as well:
if ~isa(data,'single') %# Check if data is not a single
data = single(data); %# Convert data to a single
end
See INTWARNING function to control warnings on integer operations.
http://www.mathworks.com/access/helpdesk/help/techdoc/ref/intwarning.html
精彩评论