0

While I was using seq() to generate a simple sequence with equal intervals, I found a very weird error that I was never able to understand. The example code is the following:

G <- seq(0.1,15,0.1)

And then if I test whether the sequence is correctly generated with equal interval:

G_T[97] == 9.7
G_T[101] == 10.1
G_T[102] == 10.2
G_T[103] == 10.3
G_T[104] == 10.4
G_T[105] == 10.5
G_T[106] == 10.6
G_T[107] == 10.7
G_T[108] == 10.8

and the result console shows:

> G_T[97] == 9.7
[1] FALSE
> G_T[101] == 10.1
[1] TRUE
> G_T[102] == 10.2
[1] FALSE
> G_T[103] == 10.3
[1] TRUE
> G_T[104] == 10.4
[1] TRUE
> G_T[105] == 10.5
[1] TRUE
> G_T[106] == 10.6
[1] TRUE
> G_T[107] == 10.7
[1] FALSE
> G_T[108] == 10.8
[1] TRUE

which is extremely weird as only the 97th, 102nd, 107th elements are not matched with the corresponding numbers. So I checked the differences of the numbers showing FALSE (e.g. G_T[97] - 9.7, ...), and the difference was always 0.0000000000000017764 for all the FALSE elements. Am I doing any mistakes? Or does anyone know why this happens?

  • This is a consequence of floating point arithmetic, and a very frequently asked question here on Stack Overflow (in one form or another). See the linked duplicate for a description of how ' why this happens. – Allan Cameron Mar 18 '22 at 22:56
  • Your code is not wrong. Basically your computer stores decimal numbers as an approximation to the real number. To get the outcome you are looking for, you should either (1) replace `G_T` with `round(G_T, 1)` before checking the right result, or (2) use `all.equal()` instead of `==` to check for equality while allowing a small numeric difference You can read more about "the floating point trap" in R [here](https://www.burns-stat.com/pages/Tutor/R_inferno.pdf). – jpiversen Mar 18 '22 at 23:02
  • @AllanCameron Thank you for your suggestion. I actually saw several posts that are dealing similar problems I had, but I just didn't understand them. – Junhee An Mar 18 '22 at 23:57
  • @jpiversen Thank you for your explanation. So apparently there's nothing I can do. all.equal() is not applicable when combined with which() so I'll just use round(). – Junhee An Mar 18 '22 at 23:59

0 Answers0