Potential Bug with Numbers

version
_
platform x86_64-w64-mingw32
arch x86_64
os mingw32
system x86_64, mingw32
status
major 3
minor 6.1
year 2019
month 07
day 05
svn rev 76782
language R
version.string R version 3.6.1 (2019-07-05)
nickname Action of the Toes

Hi,
There's some weird numeric issue with the version above that I'm using.
I get FALSE for 0.06 + 0.01 == 0.07 but TRUE for 0.02 + 0.05 == 0.07.
Also, I get FALSE for 0.7 %in% seq(0.1, 1, 0.1). And I get the following:

c(0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1) == seq(0.1, 1, 0.1)
[1] TRUE TRUE FALSE TRUE TRUE TRUE FALSE TRUE TRUE TRUE

Only third and seventh give FALSE. Same with %in%:

c(0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1) %in% seq(0.1, 1, 0.1)
[1] TRUE TRUE FALSE TRUE TRUE TRUE FALSE TRUE TRUE TRUE

I am not the only one having this; my coworker sees the same issue with his rstudio.
Can someone please tell me what I'm missing here? Or is this a bug?

Comparing floating numbers can be tricky when one is not aware of the following:

The only numbers that can be represented exactly in R’s numeric type are integers and fractions whose denominator is a power of 2. All other numbers are internally 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 [..] 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.

So,

0.06 + 0.01 == 0.07
#> [1] FALSE
all.equal(0.06 + 0.01, 0.07)
#> [1] TRUE

Created on 2021-02-16 by the reprex package (v1.0.0)

Thank you. That makes it clear. I did think the issue is too shallow to remain as an unfixed bug till today.
Then I guess the solution is to use some other condition in if statement.

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.