Why is Simulink giving wrong result after some basic conversion from double to uint16?

Hello everyone,
I have a very basic simulink model including basic blocks and I am performing basic logic. But simulink gives me unexpected result.
Please see the attached picture. Why after converting 4 (double) to uint16 it becomes 3 (hex)?
Any help is appreciated. I am using Matlab2012b.
Thanks, Nirav

2 Comments

I could not regenerate the same issue in ver 2013b. Looks awkward and dangerous to have such result. Eager to know the answer. I have been dealing with larger models and quite afraid now.
Found the problem. Default setting for Integer rounding for datatype conversion block is 'Floor'. I had to change it to 'Nearest'. Did you change it when you tried it?
Why should the default setting be 'Floor'?
Thanks,
Nirav

Sign in to comment.

Answers (1)

This is just floating point arithmetic, basic and simple.
Numbers like 10.20 are not exactly representable as floating point numbers, because a binary storage mode is employed, as it is in most computer languages.
sprintf('%0.55f',10.20)
ans =
10.1999999999999992894572642398998141288757324218750000000
NEVER trust the least significant bits of a computation. The following computation is a not unexpected result, because the numbers involved cannot be stored exactly, any more than you can write the fraction 2/3 exactly as a decimal with a finite number of digits.
0.3 - 0.2 - 0.1
ans =
-2.77555756156289e-17
So you need to learn to work with tolerances. It does not matter what version or release of MATLAB that you have.
Welcome to the wacky, wonderful world of floating point arithmetic.

Categories

Find more on Simulink in Help Center and File Exchange

Products

Asked:

on 10 Feb 2017

Edited:

on 11 Feb 2017

Community Treasure Hunt

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

Start Hunting!