How do I restrict a decimal number to 2 significant decimal places?
9 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
KSSV
2020-1-6
Refer for the same discussion:
3 个评论
Stephen23
2020-1-6
"...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
2020-1-6
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.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!