0

By a random chance, when I use options(digits = X), where X represents a number. My questions is when I set this X to different numbers, I could observe an interesting phenomenon in R.

When I print a numeric number, everything looks fine:

> print(1.8)
[1] 1.8

But when I set digits = 18, the number looks weird and round does not have an effect on this:

> options(digits = 18)
> 1.8
[1] 1.80000000000000004

> round(1.8, 1)
[1] 1.80000000000000004

The number looks fine when I set digits = 17:

> options(digits = 17)
> 1.8
[1] 1.8

I tested this and found that the number looks fine when digits < 18, but will have these weird looking once the digits is set to be at least 18.

Moreover, if I test if two numebers are equal using logical expressions, I have this:

> 1.80000000000000004 == 1.79999999999999999
[1] TRUE

It seesm that R internally does roundings on 1.80000000000000004 and 1.79999999999999999. My problem is: if I truly want to compare these two exact numbers (1.80000000000000004 and 1.79999999999999999), R would still think that they are the same.

Any insights on this will be appreciated. I am using R 4.1-0.

Miao Cai
  • 730
  • 5
  • 22
  • More R discussion about floating point numbers is here as well: https://stackoverflow.com/questions/9508518/why-are-these-numbers-not-equal. Computers actually aren't very good at storing decimal fractions. This is not R specific; it's common in many programming languages. You only have so many bytes to work with and computers use base-2 numbers, not base-10. – MrFlick Jul 04 '21 at 05:46

0 Answers0