MATLAB: How come “uint8(1) / 2” equals 1

integer arithmeticsMATLABuint8

MATLAB believes that "uint8(1) / 2" equals 1 and mod(uint8(1),2) equals 1 as well. It does not make any sense to me. I believe that general rule of integer arithmetics is "a equals (a/b)*b + a mod b", so usually "uint8(1) / 2" is 0. It is certainly so in C/C++ and FORTRAN, I do not really recall any language where it is different. Why is it 1 in MATLAB?

Best Answer

Operations on integer data types are carried out as if the values are converted to double before the operation and then the result is converted to the most restrictive data type of the opetands. Converting double to uint8 is defined to round. uint8(1/2) rounds to 1.
Notice that uint8(1)/2 is an operation on mixed data types since the 2 is double precision.