Detect variable overflow in matlab code

조회 수: 8 (최근 30일)
Stefan
Stefan 2021년 2월 11일
답변: Mohammad Sami 2021년 3월 10일
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?

채택된 답변

Mohammad Sami
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개)

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

제품


릴리스

R2020b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by