How come "uint8(1) / 2" equals 1?

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?

1 Comment

" Why is it 1 in MATLAB?"
Ask Cleve Moler.

Sign in to comment.

 Accepted Answer

Walter Roberson
Walter Roberson on 19 Sep 2017
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.

2 Comments

See the "Creating Integer Data" and "Arithmetic Operations on Integer Classes" sections on this documentation page for more information.

Sign in to comment.

More Answers (0)

Products

Community Treasure Hunt

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

Start Hunting!