I am writing a function in R that requires me to increment a counter by 0.05. When I condition on the value of the counter I am getting told that the value is not what it appears.
Example:
Set the counter to 0
cntr <- 0; cntr;
[1] 0
Increment counter by 0.05 and test
cntr <- cntr + 0.05; cntr;
[1] 0.05
> cntr == 0.05
[1] TRUE
So far, so good. But after a couple more iterations the following happens:
> cntr <- cntr + 0.05; cntr;
[1] 0.1
> cntr == 0.1
[1] TRUE
> cntr <- cntr + 0.05; cntr;
[1] 0.15
> cntr == 0.15
[1] FALSE
What is happening, and why? The value returned for cntr is 0.15 but it is not equal to this value?
Further investigation reveals this:
> cntr < 0.1500000000000001
[1] TRUE
> cntr < 0.15000000000000001
[1] FALSE
and
round(cntr, 2) == 0.15
[1] TRUE
Am I misunderstanding something, or is there something I am not seeing? Any help would be greatly appreciated. Thank you.
You have to use
isTRUE(all.equal(cntr, x)), where x is 0.1, 0.05, etc. instead. Your tests are failing because of floating point rounding errors.all.equaltests equality up to that error. Check out Circle 1 in R Inferno for other examples of where this might trip you up.