Matlab中浮点比较的最佳实践 [英] Best Practice for Float Comparison in Matlab
问题描述
是否有快速简单的方法来执行这些检查?
我能想到的最简单的方法是构建一个用于固定公差float比较的自定义函数,但对我来说这似乎相当难看。我更喜欢一个内置的解决方案,或者至少是一些非常清晰和直截了当的理解。
感谢您的输入!
我认为这很可能将不得不是你自己写的一个函数。我经常用三样东西来运行计算向量测试:
最大绝对误差
return max(abs(result(:) - expected(:)))<容差
这个方法可以计算出最大的绝对误差,并告诉你这个误差是否小于某个误差。 p>
最大错误计数
((abs(result() - expected(:)))< tolerance)
超出公差范围的点数。
均方根误差
return norm(result(:) - expected(:)) rmsTolerance
由于这些和许多其他标准存在比较浮点数组,我会建议写一个函数将接受计算结果,预期结果,容差和比较方法。这样你就可以使你的支票变得非常紧凑,而且比试图解释你在评论中做什么要容易得多。
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 straigthforward to understand.
Thanks for your input!
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:
Maximum absolute error
return max(abs(result(:) - expected(:))) < tolerance
This calculates maximum absolute error point-wise and tells you whether that's less than some tolerance.
Maximum excessive error count
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.
Root mean squared error
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.
这篇关于Matlab中浮点比较的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!