Best practise for handling float precision in R?

I'm interested in best practises for the following issue, which requires careful handling:

> 0.1 + 0.2 == 0.3
[1] FALSE

We can do

> all.equal(0.1 + 0.2, 0.3)
[1] TRUE

or

> t = 1e-10
> abs(0.1 + 0.2 - 0.3) <= t
[1] TRUE

But is there a best practise I wonder?

I was under the impression that all.equal is the best practice in this case. At least that what I understood from the help-file for all.equal. I've been also recommending it couple of times, so I hope it is the best practice :slight_smile:

1 Like

The approach suggested by R4DS (as close to best practices as I can think) is near()

library(tidyverse)

.1 + .2 == .3
#> [1] FALSE

near(.1 + .2, .3)
#> [1] TRUE

Thanks for the hint :+1:

I can see, that internally near() does the same as my last example:

> near
function (x, y, tol = .Machine$double.eps^0.5) 
{
    abs(x - y) < tol
}
<environment: namespace:dplyr>

Where

> .Machine$double.eps^0.5
[1] 1.490116e-08

So using a tolerance of 1.5e-08, rather than the 1e-10 in my example :slightly_smiling_face:

To be honest this is a simple problem, there are not that many possible solution to pick from.

The devil in details is about 1) being aware of it at all (some CS background helps) and 2) being consistent in applying your tolerances

1 Like

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.