How do I restrict a decimal number to 2 significant decimal places?
9 views (last 30 days)
Show older comments
I am using a decimal number as follows
x = 3.43 on my command window
I want this number to be used as a single data type, which means I have to write as follows
x = single(3.43)
I am trying to see how long the decimal places are precisely correct for that I am using
format long
However I am facing problem when I try to convert and decimal number into single data type equivalent decimal number
x = single(3.43)
x =
single
3.4300001, this 1 at the end is not required for my calculations, as it creates rounding off problems in my simulation(Simulink)
let me know how can I restrict this value.
Thanks
0 Comments
Accepted Answer
KSSV
on 6 Jan 2020
Refer for the same discussion:
3 Comments
Stephen23
on 6 Jan 2020
"...it is not properly rounding off to the closes number."
Yes it is.
Here are the Single floating point numbers around that value:
>> x = single(3.43)
x =
3.4300001
>> x-eps(x)
ans =
3.4299998
>> x+eps(x)
ans =
3.4300003
Can you show a Single floating point number that is closer to your value? I bet you can't.
Lets take a look at the actual binary value stored in memory, as hexdecimal for convenience:
>> typecast(uint32(hex2dec('405b851f')),'single') % x
ans =
3.4300001
>> typecast(uint32(hex2dec('405b851e')),'single') % x-eps
ans =
3.4299998
>> typecast(uint32(hex2dec('405b8520')),'single') % x+eps
ans =
3.4300003
What Single floating point number do you expect to find between those possible Single floating point numbers? (hint: it would have to representable as a hexadecimal digit between 'e' and 'f', something that I am sure that many computer scientists would be very surprised to see).
Guillaume
on 6 Jan 2020
To be very clear: Computers cannot store the number 3.43 exactly as single (or double for that matter). The number will be stored as its nearest representable value which is 3.4300000667572021484375 as single, or 3.430000000000000159872115546022541821002960205078125 as double.
More Answers (0)
See Also
Categories
Find more on Logical 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!