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;

[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

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


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.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

Need Your Help

Code Igniter Validation on Error

php codeigniter oop

I am pretty knew to code igniter / OOP but I am giving it a shot and a little stumped at this point.

Meteor : Access to my public/lib from server


According to the Meteor Doc, the public fodler is accessible for both server and client. But, if I just need to use the HTML head elements to access it, how can I do it from server ?

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.