Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

r - Exactly storing large integers

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...