2

I would like to generate a random 20-digit number using R.

My first attempt was to do

runif(1,10000000000000000000,9999999999999999999)

But this doesn't seem to work because R keeps rounding the 9999999999999999999 to 10000000000000000000. It doesn't seem to accept a "9999" number until I go down to 15 digits:

> 9999999999999999999
[1] 10000000000000000000
> 999999999999999999
[1] 1000000000000000000
> 99999999999999999
[1] 100000000000000000
> 9999999999999999
[1] 10000000000000000
> 999999999999999
[1]  999999999999999
> 99999999999999
[1]  99999999999999
> 9999999999999
[1]  9999999999999

Is there a better way to approach this?

bobfet1
  • 1,603
  • 21
  • 22

2 Answers2

9

You can generate this number as a string:

paste( sample( 0:9, 20, replace=TRUE ), collapse="" )
# [1] "40910135645767200675"
Vincent Zoonekynd
  • 31,893
  • 5
  • 69
  • 78
1
set.seed(1)
sprintf("%20.0f",runif(1,1e19,1e20))
#[1] "33895779682788999168"
dayne
  • 7,504
  • 6
  • 38
  • 56
  • 1
    This may be platform-dependent, but it is too close from the precision of the machine: the last digit is always even... – Vincent Zoonekynd Sep 20 '13 at 18:53
  • At first I thought this was generating randomly, but when I do it on my machine, I see the same issue Vincent mentions where it is always even – bobfet1 Sep 20 '13 at 18:59
  • The same thing happens for me. Wonder why the last number is always even? – dayne Sep 20 '13 at 19:00
  • this *is* curious - try `sprintf("%.0f",runif(1,1e29,1e30))` - the last 10 digits or so are always even – eddi Sep 20 '13 at 19:03
  • 6
    Floating point numbers are actually encoded in binary form, with a limited number of binary digits. If we exceed the limit, the last binary digits are deemed non-significant: they are not stored, and assumed to be zero. Numbers ending with 0 in binary are multiples of 2, numbers ending in 00 multiples of 4, etc. – Vincent Zoonekynd Sep 20 '13 at 19:03
  • Apparently, it has to round even before the sprintf is done...looking at `print(runif(1,1e19,1e20),digits=22)`. Here's what I dug out: http://stackoverflow.com/questions/2053397/long-bigint-decimal-equivalent-datatype-in-r – Frank Sep 20 '13 at 19:05
  • 6
    The classical reference for those problems is: [What Every Computer Scientist Should Know About Floating-Point Arithmetic](http://download.oracle.com/docs/cd/E19422-01/819-3693/ncg_goldberg.html). – Vincent Zoonekynd Sep 20 '13 at 19:07