Version 0.2.0 of
fpCompare
has been released on CRAN
Comparisons of floating point numbers are problematic due to errors associated with the binary representation of decimal numbers. Computer scientists and programmers are aware of these problems and yet people still use numerical methods which fail to account for floating point errors (this pitfall is the first to be highlighted in Circle 1 of Burns (2012) The R Inferno).
Inspired by R FAQ 7.31 and this Stack Overflow answer, the fpCompare
package provides new relational operators useful for performing floating point number comparisons with a set tolerance:
set.seed(123)
<- 1:6
a <- jitter(1:6, 1e-7)
b print(rbind(a,b), digits=16)
%<=% a # b <= a
b %<<% a # b < a
b %>=% a # b >= a
b %>>% a # b > a
b %==% a # b == a
b %!=% a # b != a b
These functions use the base
relational operators to make comparisons, but incorporate a tolerance value (fpCompare.tolerance
), set via options
. It uses the same default tolerance value used in all.equal
for numeric comparisons.
# set telorance value
= .Machine$double.eps^0.5 # default value
tol options(fpCompare.tolerance = tol)
# perform comparisons
<- 0.5 - 0.3
x1 <- 0.3 - 0.1
x2 == x2 # FALSE on most machines
x1 %==% x2 # TRUE everywhere x1
Installation
From CRAN
install.packages("fpCompare")
From GitHub
library(devtools)
install_github("PredictiveEcology/fpCompare")