Floating point almost equal

7 posts in this topic

The other day I encountered a situation where I wanted to test if two floating point values were equal. Of course, one of the first things that you are told about floating point values is that you should never test for exact equality. So I proceed to wire up:


Is X = Y +/- some acceptable tolerance?


And that worked perfectly for my use case. That is, I knew that the max. value was 1000 and the min value was 0 and the resolution (or increment) was 0.01. A tolerance of 0.001 was sufficient.


This got me thinking. Wouldn't it be nice to have some reusable VIs for testing if floating point values are almost equal? Unfortunately this meant taking a broader view of the problem and lead me to this interesting blog post:




I've attached VIs for the Absolute Epsilon comparison, Relative Epsilon comparison and the ULP comparison described in the blog post for double precision floating point values.




Perhaps this would be a nice addition to the somewhat barren OpenG Comparison Pallet?


Uploaded package to Code Repository: http://lavag.org/files/file/259-floating-point-almost-equal/



Edited by Porter

Share this post

Link to post
Share on other sites

Altenbach has a version, MGI has a version, and I've seen several other implementations of it.  There also exists a primitive in LabVIEW that isn't on the palette that does this, but several NI employees have said it is not stable and not to use it.

Share this post

Link to post
Share on other sites
Thanks for the info.


MGI's solution looks somewhat like the relative epsilon solution proposed in Bruce Dawson's blog post however they use a fixed maximum relative difference of 1%. Perhaps in some cases that would be too high.


Altenbach's version looks identical to the AlmostEqual2sComplement() function described in another article by Bruce Dawson:


Notice at the top of that article he states that you should not be using that method of comparison as it has a couple of major flaws. For example, comparing 2 and -2 will always return true. 


I have added the relative epsilon comparison to the package for completeness. This way, you can try all 3 methods if you are interested. Most of the time I really only need the absolute epsilon comparison because I know beforehand what range of values I'm comparing.

Share this post

Link to post
Share on other sites

Saved to LV 8.6

Share this post

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now