1

Problem with precision in R

When I multiply a high precision double value number in R the precision seems to change or something weird happens. Look at the last 4 digits.

x <- 1608781598.186771296
y<-1000000000.00
print(x*y)
#1608781598186771456

#turns out that R is converting the precision like so
print(as.double(1608781598.186771296),digits=19)
#1608781598.186771393
#if I use the above value and multiply by a billion I can reproduce the incorrect value
print(1608781598.186771393*1000000000.0)
#1608781598186771456

Similar problem in python

In fact similar thing is happening in Python as well

import numpy as np
print("{:.0f}".format(np.float128(1608781598.186771296)*np.float128(1000000000)))
#1608781598186771456

Whereas I am expecting a value of 1608781598186771296. What the heck is going on in here?

  • Most languages don't store number with infinite precision. Some rounding occurs. See https://stackoverflow.com/questions/9508518/why-are-these-numbers-not-equal – MrFlick Dec 24 '20 at 06:41
  • I am not looking for infinite precious but at least till 19th significant digits – Lawrence Khan Dec 24 '20 at 07:16
  • I'm afraid that's not possible with R's native numeric types (and most other programming languages). Even values like 0.15 can't be stored accurately with floating points numbers: `print(0.15, digits=20)`. That's why `0.10+0.05==0.15` returns FALSE. If you need to track such numbers, one trick it to store the integer part and the fractional part as two separate integers. – MrFlick Dec 24 '20 at 07:24

1 Answers1

2

In R, each double or decimal value is accurate upto 16 significant digits. Your 'x' has more than 16 significant digits, so would have already rounded the 'x' variable while storing. Hence the discrepancy.

Karthik S
  • 11,348
  • 2
  • 11
  • 25
  • 2
    I am not quite sure if I want to believe this. Because take a look how R converting the precision. `print(as.double(1608781598.186771296),digits=19)` `#1608781598.186771393` `1608781598.186771393 * 1000000000.0` `#1608781598186771456` – Lawrence Khan Dec 24 '20 at 07:12