Interesting unequal math equation

Well, I saw an interesting problem this morning. See the code below.

> 1.37+0.12 == 1.49
> 1.36+0.12 == 1.48
[1] TRUE

It looks weird, right? I googled this problem and someone gives an explanation like this: “Most float number has no exact representation in binary format, just approximation”. The  interpretation isn’t so clear, but at least we know what’s going on.

> 1.37+0.12-1.49
[1] 2.220446e-16
> 1.36+0.12-1.48
[1] 0

So, if you need this kind of comparison in an if control structure, you may have some trouble. One solution is that writing code in this way: 1.37+0.12-1.49 > -1e-10 and 1.37+0.12-1.49 < 1e-10. Looks ugly, but it works.

And there is also a better way to handle this in R. The all.equal() function is what we need.  The function is used to test if two objects are nearly equal.

> if (1.37+0.12 == 1.49) {cat('Match')}
> if (-1e-10 < 1.37+0.12-1.49 & 1.37+0.12-1.49 < 1e-10)
+ {cat('Match')}
> if (all.equal(1.37+0.12, 1.49)) {cat('Match')}
Posted in R Programming Tips.

Leave a Reply

Your email address will not be published. Required fields are marked *