Detect variable overflow in matlab code
조회 수: 8 (최근 30일)
이전 댓글 표시
I have an applicaiton where I keep adding an integer value to an other integer. In the simple example below I keep adding temp to i. If i reach the maximum value of this integer matlab will saturate the result to be intmax('uint8'). But what I actually want is it not to saturate. For instance if i == uint8(255) and I add 1. Than the value of i should be 0. If this happends I want to run some different code.
i = uint8(0);
for j = 1:10000
temp = uint8(rand*10);
i = i + temp;
if i == intmax('uint8')
disp('max reached')
end
end
Now we do this by check if the sum would saturate the variable:
i = uint8(0);
for j = 1:10000
temp = uint8(rand*100);
if (i + temp) == intmax('uint8')
disp(['max reached ' num2str(i) ' ' num2str(temp)] )
i = temp - (intmax('uint8') - i);
disp(num2str(i))
else
i = i + temp;
end
end
This almost works but if the sum is exectly 255 we make a mistake of 1. Does anyone know if there is a function or a method to do this in an other way?
댓글 수: 0
채택된 답변
Mohammad Sami
2021년 3월 10일
The following should work.
i = uint8(0);
for j = 1:10000
temp = randi(255,'uint8');
% test if temp is bigger then the difference between intmax and i
if temp > (intmax('uint8') - i)
disp(['max reached ' num2str(i) ' ' num2str(temp)] )
i = temp - (intmax('uint8') - i);
disp(num2str(i));
else
i = i + temp;
disp(num2str(i));
end
end
댓글 수: 0
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Logical에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!