Exactly storing large integers
Asked Answered
S

1

7

In R software

a <- 123456789123456789123456789
sprintf("%27f",a)
#[1] "123456789123456791337762816.000000"

I got the wrong answer. I want exact a value.

Why is the system showing the wrong value of a?

Suchlike answered 3/9, 2015 at 6:37 Comment(2)
Also check herePostdiluvian
As explained in this comment (under a duplicate question), do not forget to pass a character when using gmp::as.bigz().Wilbourn
R
10

The reason you're not getting your exact value of a is that R is storing it as a double instead of as an integer. Because a is very large, there is some rounding that takes place when you assign a.

Normally to store things as integers you would use L at the end of the numbers; something like:

a <- 12L
class(a)
# [1] "integer"

However your number is too large for a standard integer in R, and you're forced to use the double representation:

a <- 123456789123456789123456789L
# Warning message:
# non-integer value 123456789123456789123456789L qualified with L; using numeric value 
class(a)
# [1] "numeric"

You will need multiple precision to exactly store an integer this large. One option would be the gmp package:

library(gmp)
a<-as.bigz("123456789123456789123456789")
a
# Big Integer ('bigz') :
# [1] 123456789123456789123456789

Other options for multi-precision arithmetic are available under the "Multi-Precision Arithmetic and Symbolic Mathematics" subheading of the numerical mathematics CRAN task view.

Runway answered 3/9, 2015 at 6:43 Comment(3)
a<-as.bigz("2*3*7*43*1807*3263443") If i type like this, Big Integer ('bigz') : [1] NA it shows like this, so what i do?Suchlike
@Suchlike you should store each as a bigz and then multiply; something like prod(as.bigz(c(2, 3, 7, 43, 1807, 3263443)))Runway
factorize( 113423713055421844361000443) and factorize(113423713055421845118910464) have the same answer what i do?Suchlike

© 2022 - 2024 — McMap. All rights reserved.