Why not getting same constant value after converting to single from double in MATLAB 2016b simulink
4 views (last 30 days)
Show older comments
I have a implemented below logic in simulink
double a = 0.01;
b = single(a);
Expected value is 0.01 but getting 0.0099999123412 (in display block with format long).
What to do to get exact value?
Configurations settings:
fixed step, auto solver
step size : 0.01
Please let me know how get exact value.
0 Comments
Answers (2)
John D'Errico
on 24 Jul 2023
Welcome to the wonderful wacky world of floating point arithmatic.
I think you don't understand floating point arithmetic. 0.1 is NOT representable in floating point arithmetic. You CANNOT get an exact value, as a single OR a double. It does not exist.
Perhaps you think it does. But can you represent 1/3 or 2/3 as exact numbers as a decimal in a FINITE number of decimal digits? If you cannot do that, you must accept that other numbers will also have problems. Remember that singles and doubles are stored in a BINARY form, NOT as decimals. This is a fact of using a computer, in literally any programming language. They use an IEEE standard for number storage.
In binary, 0.1 would be the infinite bit sequence
0.00011001100110011001100110011...
where the ones represent negative powers of 2.
So what you see is probably a 1 bit error down at the level of the least significant bit for a single.
Andy Bartlett
on 24 Jul 2023
Edited: Andy Bartlett
on 24 Jul 2023
The facts that John D'Errico mentioned are very good to keep in mind as you are analyzing/debugging your model.
The rounding of an ideal decimal value in text to a floating-point value can produce half an eps of error.
Likewise displaying a floating point value in decimal text using long format can introduce a few eps of inaccuracy.
However, for your model, the difference between what you observed and what you expected is 94 eps.
format long e
val1 = single(0.01)
val2 = single(0.0099999123412)
valDiff = val1 - val2
epsSingle0p1 = eps(val1)
differenceInBits = valDiff / epsSingle0p1
94 eps of error suggests that math operations in your model have accumulated round off errors, such as through addition and subtraction, or amplified those round off errors, such as through multiplication.
I think you'll have to analyze your model more closely to see where the original round off errors are introduced and how they are built-up through calculations. Simulink's stepper capability is very helpful for this kind of debugging.
Again keep in mind, the floating-point representation issues that John mentioned and the inaccuracies that even format long can have in displaying values. It may be helpful to read the following for more information related to that topic.
0 Comments
See Also
Categories
Find more on Simulink Functions in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!