且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在MATLAB中更改浮点精度将5.145556666视为5.24

更新时间:2021-12-31 03:20:30

如果您只想显示仅2位数字的值,则可以

If you want to display values with only 2 digits, you can do

>> format bank
>> pi
ans = 
    3.14
>> rand(4)
ans =
      0.81    0.63    0.96    0.96
      0.91    0.10    0.96    0.49
      0.13    0.28    0.16    0.80
      0.91    0.55    0.97    0.14

这确实 NOT 意味着计算将以较低的精度进行.

This does NOT mean calculations will be carried out with less precision.

如果后者确实是您想要的(为什么?!),则可以使用类似的构造

If the latter is really what you want (why?!), you could use constructions like

ppi = single(pi)

降低精度,或

f = @(x) double(uint64(x*100))/100;

用于保证两位数精度.在最后一种情况下,必须在使用所有值之前通过函数f进行传递:

for guaranteed 2-digit precision. In the last case, you have to pass all values through the function f prior to using them:

>> ppi = f(pi)
ans = 
    3.140000000000000
>> f(rand(4)) 
ans =
   0.280000000000000   0.690000000000000   0.440000000000000   0.190000000000000
   0.050000000000000   0.320000000000000   0.380000000000000   0.490000000000000
   0.100000000000000   0.950000000000000   0.770000000000000   0.450000000000000
   0.820000000000000   0.030000000000000   0.800000000000000   0.650000000000000

如果您正在为后一种情况寻找更优雅的解决方案,请使用Danil建议的定点工具箱.

If you're looking for a more elegant solution for this last case, use the fixed-point toolbox, as Danil suggested.