Matlab中浮点比较的最佳实践是什么?
很明显,浮点数比较总是很棘手.我的(科学的)代码中有很多断言检查,因此很多时候我必须检查总和是否相等以及类似的问题.
Obviously, float comparison is always tricky. I have a lot of assert-check in my (scientific) code, so very often I have to check for equality of sums to one, and similar issues.
是否有一种快速,简便/最佳实践的方式来执行这些检查?
Is there a quick-and easy / best-practice way of performing those checks?
我能想到的最简单的方法是建立一个用于固定公差浮点比较的自定义函数,但这对我来说似乎很丑陋.我希望使用内置解决方案,或者至少要非常清楚易懂的东西.
The easiest way I can think of is to build a custom function for fixed tolerance float comparison, but that seems quite ugly to me. I'd prefer a built-in solution, or at least something that is extremely clear and straightforward to understand.
我认为最有可能必须是您自己编写的函数.可以这么说,我经常使用三件事来运行计算矢量测试:
I think it's most likely going to have to be a function you write yourself. I use three things pretty constantly for running computational vector tests so to speak:
最大绝对错误
return max(abs(result(:) - expected(:))) < tolerance
这将逐点计算最大绝对误差,并告诉您是否小于某个公差.
This calculates maximum absolute error point-wise and tells you whether that's less than some tolerance.
最大错误计数上限
return sum( (abs(result(:) - expected(:))) < tolerance )
这将返回超出公差范围的点数.修改返回百分比也很容易.
This returns the number of points that fall outside your tolerance range. It's also easy to modify to return percentage.
均方根误差
return norm(result(:) - expected(:)) < rmsTolerance
由于存在用于比较浮点数数组的这些条件和许多其他条件,因此我建议编写一个函数,该函数将接受计算结果,预期结果,公差和比较方法.这样,您可以使检查变得非常紧凑,并且比试图解释注释中的操作要丑陋得多.
Since these and many other criteria exist for comparing arrays of floats, I would suggest writing a function which would accept the calculation result, the expected result, the tolerance and the comparison method. This way you can make your checks very compact, and it's going to be much less ugly than trying to explain what it is that you're doing in comments.