R incrementing by decimal value does not return expected value
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.
Set the counter to 0
cntr <- 0; cntr;
Increment counter by 0.05 and test
cntr <- cntr + 0.05; cntr;  0.05
> cntr == 0.05  TRUE
So far, so good. But after a couple more iterations the following happens:
> cntr <- cntr + 0.05; cntr;  0.1 > cntr == 0.1  TRUE > cntr <- cntr + 0.05; cntr;  0.15 > cntr == 0.15  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  TRUE > cntr < 0.15000000000000001  FALSE
round(cntr, 2) == 0.15  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.equal tests equality up to that error. Check out Circle 1 in R Inferno for other examples of where this might trip you up.
In a broader sense, you look like you are pretty new to R programming, and I want to ask why you are trying to use a counter. In general, R discourages the use of loops, especially loops with counters in them. If you are using a loop with a counter, it is likely that you can vectorize your function to improve the efficiency of your code.
One other approach to this could be to use an integer and to increment by 5. When you need to use the incremented value, divide by 100.
The problem you have illustrated is due to how decimal values are stored in computer programs when using a binary format; it is not a problem specific to R. You can read more about the reasons for this here