Version 0.2.0 of
fpComparehas 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).
set.seed(123) a <- 1:6 b <- jitter(1:6, 1e-7) print(rbind(a,b), digits=16) b %<=% a # b <= a b %<<% a # b < a b %>=% a # b >= a b %>>% a # b > a b %==% a # b == a b %!=% a # b != a
These functions use the
base relational operators to make comparisons, but incorporate a tolerance value (
fpCompare.tolerance), set via
It uses the same default tolerance value used in
all.equal for numeric comparisons.
# set telorance value tol = .Machine$double.eps^0.5 # default value options(fpCompare.tolerance = tol) # perform comparisons x1 <- 0.5 - 0.3 x2 <- 0.3 - 0.1 x1 == x2 # FALSE on most machines x1 %==% x2 # TRUE everywhere