how to get floating point number upto 4 decimal points
12 次查看(过去 30 天)
显示 更早的评论
hi i have an array of floating point numbers of type double...for example x=[ 0.8462 0.4906 0.9422 0.2054 0.6154 0.8923 0.3622 0.8710 0.4237 0.9206 0.2757 0.7528] how to limit the values upto 4 decimal points.
x11=(round(x*10000))/10000; does not work
0 个评论
采纳的回答
Walter Roberson
2017-1-30
vpa(sym(x), 4)
will give you 4 digit symbolic numbers.
arrayfun(@(X) sprintf('%.4f',X), x, 'uniform', 0)
Or
cellstr(num2str(x(:), '%.4f')).'
will give you a cell array of strings representation.
round(x*10000)
will give you integers with an implied decimal point.
But if you are looking for floating point values with exactly 4 decimal places then the symbolic version is as close as you can get. The fraction 1/10 requires an infinite repeating value in binary, just like 1/7 requires an infinite repeating value in decimal. You just cannot represent 0.8462 exactly in binary.
3 个评论
Walter Roberson
2017-1-30
vpa is not defined on numeric values, only on symbolic values.
mod(x, 1) gives you the fractional part for nonnegative values. For negative values you need to define whether you want the offset from the lower integer or if you want the offset from the higher integer. -0.25 is 0.75 above the integer below it, but you might be looking for the 0.25 part. If so then use mod(abs(x), 1)
You would then apply one of the above to get the number in the form you want, keeping in mind that it is not possible to exactly represent most fractions. Only 16 of the 4 digits decimal fractions can be exactly represented in binary.
Walter Roberson
2017-8-23
More recently I have discovered that vpa() does not represent floating point numbers in decimal internally.
更多回答(1 个)
Guillaume
2017-1-30
In what way does
x11 = round(x*10000)/10000 %could be simply replaced by round(x, 4)
not work?
>>round(pi*10000)/10000
ans =
3.1416
>>round(pi, 4)
ans =
3.1416
If you are talking about how the numbers are display, note that it has nothing to do with the actual value stored in the number. You use the format command to tell matlab how to display the numbers. Personally, I use
format shortg
4 个评论
Walter Roberson
2017-8-23
Also note that round() only finds the closest representable number, which will seldom be exactly the value being looked for. It is not possible to represent 0.23 (23/100) exactly in finite binary floating point.
Jan
2019-4-3
i used 'shortg' before my string and i got the limited number string ... provided command was helpful for me . thank you !!!!!
@Vithal Bable: Please use flags only to inform admins and editors about inappropriate contents like spam or rudeness. Thanks.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!