7.31 Why doesn’t R think these numbers are equal?
The only numbers that can be represented exactly in R’s numeric type are integers and fractions whose denominator is a power of 2. Other numbers have to be rounded to (typically) 53 binary digits accuracy. As a result, two floating point numbers will not reliably be equal unless they have been computed by the same algorithm, and not always even then. For example
R> a <- sqrt(2)
R> a * a == 2
[1] FALSE
R> a * a - 2
[1] 4.440892e-16
The function all.equal() compares two objects using a numeric tolerance of .Machine$double.eps ^ 0.5. If you want much greater accuracy than this you will need to consider error propagation carefully.
If you're expecting a result to be an integer, you could force it to be a perfect one by using the round
function:
7L - (.05+.1)/.05 == 4
[1] FALSE
round(7L - (.05+.1)/.05) == 4
[1] TRUE