4

How is this expression TRUE?

(13532728 + 1 + 76561197960265728) == (13532740 + 1 + 76561197960265728)

I calculated both expressions separated and they result in the same value:

Both: (13532728 + 1 + 76561197960265728) and (13532740 + 1 + 76561197960265728) are resultin in the same value:76561197973798464 in my R workspace. Which is clearly wrong, only the first number changes in both sides.

I thought it could be an overflow error. But isn't the max value of numeric .Machine$double.xmax which is huge.

Anyone can explain me why the calculation is wrong in R ?

Gregor Thomas
  • 136,190
  • 20
  • 167
  • 294
  • 2
    I think this is closely related to https://stackoverflow.com/q/9508518/3358272 and https://cran.r-project.org/doc/FAQ/R-FAQ.html#Why-doesn_0027t-R-think-these-numbers-are-equal_003f; they are related because they both deal with the presumption that floating-point storage perfectly preserves all digits, which they do not. – r2evans Sep 08 '22 at 01:23
  • 1
    I don't have a good answer for why there is loss of precision for 16 digit integer values of class `numeric`, but there are plenty of packages that solve the issue. `bit64` is plenty for this, or a package like `gmp` gives you as much integer precision as you could need. – Gregor Thomas Sep 08 '22 at 02:45
  • It was indeed a loss of precision error. Bit64 solved the issue. Thanks – Gustavo Gomes Sep 08 '22 at 03:45

0 Answers0