Matlab中浮点比较的最佳实践是什么? [英] What are the best practices for floating-point comparisons in Matlab?

查看:72
本文介绍了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.

这篇关于Matlab中浮点比较的最佳实践是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆