What are the best practices for floating-point comparisons in Matlab?

后端 未结 5 950
时光取名叫无心
时光取名叫无心 2020-12-03 11:02

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 is

5条回答
  •  悲哀的现实
    2020-12-03 11:36

    I have had good experience with xUnit, a unit test framework for Matlab. After installing it, you can use:

    • assertVectorsAlmostEqual(a,b) (checks for normwise closeness between vectors; configurable absolute/relative tolerance and sane defaults)
    • assertElementsAlmostEqual(a,b) (same check, but elementwise on every single entry -- so [1 1e-12] and [1 -1e-9] will compare equal with the former but not with the latter).

    They are well-tested, fast to use and clear enough to read. The function names are quite long, but with any decent editor (or the Matlab one) you can write them as assertV.

提交回复
热议问题