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?

josliber
  • 43,000
  • 12
  • 95
  • 132
aarthi
  • 85
  • 5
  • Also check [here](http://stackoverflow.com/questions/32339636/long-numbers-as-a-character-string) – akrun Sep 03 '15 at 06:48
  • As explained in [this comment](http://stackoverflow.com/questions/40419024/is-there-a-way-to-display-frank-nelson-coles-factors-of-267-%e2%88%92-1-correctly-with#comment68089039_40419024) (under a duplicate question), do not forget to pass a character when using `gmp::as.bigz()`. – Paul Rougieux Nov 04 '16 at 10:32

1 Answers1

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.

josliber
  • 43,000
  • 12
  • 95
  • 132