Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
375 views
in Technique[技术] by (71.8m points)

What are the best practices for floating-point comparisons in 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...