MATLAB浮点数精度问题

最近在使用MATLAB做一个数据分析的项目时,遇到了一个非常隐藏的bug,花了好久终于发现了问题所在——精度的问题导致同样的数字在MATLAB中并不是相等。举一个简单的例子比如:a=1.065000000000000e+05和b=106500,若判断二者是否相等将返回不相等。

通常来说,判断完全相等,我们会使用“==”。但在实际的应用中,对于浮点数来说,“完全相等”无法得到我们想要的结果,相比之下,“在一定的精度范围内相等”更准确一些。

相应的解决办法有:

1. 使用round函数

round(X) rounds each element of X to the nearest integer.

round(X, N), for positive integers N, rounds to N digits to the right of the decimal point. If N is zero, X is rounded to the nearest integer. If N is less than zero, X is rounded to the left of the decimal point. 

round(pi, 2) = 3.14

2. 使用两者做差使得他们的差都小于一个非常小的数

3. 类似于2,使用eps

猜你喜欢

转载自blog.csdn.net/u012111475/article/details/80984619