1

I was trying to develop a program in R Studio which needed the user to input any number as they wish which can even be huge. So I was experimenting giving random numbers and got a problem. When I entered a huge number every time the R displayed incorrectly. I restarted R session .. still the problem persists. Please help. Here is the snapshot of what problem I am encountering.

enter image description here

  • You are probably exceding the precision of the numeric/integer type here. Question: Do you really need to worry about the tens place precision in a number which is in the billions/trilions? – Tim Biegeleisen Dec 14 '20 at 06:23
  • Does this answer your question? [Max Length for a Vector in R](https://stackoverflow.com/questions/10640836/max-length-for-a-vector-in-r) – Daman deep Dec 14 '20 at 06:27
  • I was trying to write a program which converts numbers to its word representation. Hence if the input number changes it should will display the word representation incorrectly. Also if u can see the the output number has same number of digits as the input but the number is incorrect. – Nithin Nayak Dec 14 '20 at 06:31
  • https://stackoverflow.com/questions/54681480/r-how-to-convert-long-number-to-string-to-save-precision/54694017#54694017 – Ben Bolker Dec 14 '20 at 23:21

1 Answers1

2

You've exceeded the amount of data you can represent in R's integers (32-bit signed): −2,147,483,648 to 2,147,483,647. There's an option to extend to 64 bits using the bit64 package, as per Ben Bolker's comment below). This would extend your range from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807.

If you need more precision than that, try the gmp library. Note that the integer is presented as a character, to avoid precision effects rounding the number before it's processed.

options(scipen=99)
a1 <- 123456789123456789123456789
a1
[1] 123456789123456791346468826
a1 - (a1 -1)
[1] 0

# now using arbitrary-precision (big) numbers
library(gmp)
b1 <- as.bigz("123456789123456789123456789")
b1
Big Integer ('bigz') :
[1] 123456789123456789123456789

b1 - (b1 -1)
Big Integer ('bigz') :
[1] 1
Jason
  • 2,507
  • 20
  • 25
  • Good answer, although base-R integers are only 31 bits (and 1 sign bit): `.Machine$integer.max` is 2^31-1. There is a `bit64` package that enables 64-bit integers (but as you point out, this is well beyond that range). – Ben Bolker Dec 14 '20 at 23:18