Generate integer random numbers from range (0:10^12)

后端 未结 5 1483
予麋鹿
予麋鹿 2021-01-07 17:54

I want to generate 10000 integer random numbers between 0 and 10^12. Usually, the code would look like this:

x <- sample(0:1000000000000,10000,replace=T)
         


        
5条回答
  •  既然无缘
    2021-01-07 18:34

    The real problem lies in the fact that you cannot store the sequence of 0:10^12 into memory. By just defining 0 and 10^12 as boundaries of a uniform distribution, you could get what you seek:

    runif(10000, 0, 10^12)
    [1] 136086417828 280099797063 747063538991 250189170474 589044594904
    [6]  65385828028 361086657969 186271687970 338900779840 649082854623  ........
    

    This will draw from the uniform distribution (with replacement, though I doubt that matters).

    However, what you cannot see is that these are actually floating numbers.

    You can use ceiling to round them up:

    samp = runif(1, 0, 10^12)
    samp
    [1] 19199806033
    samp == 19199806033
    [1] FALSE
    ceiling(samp) == 19199806033
    [1] TRUE
    

    So the full code would be:

    ceiling(runif(10000, 0, 10^12))
    

    Further nitpicking:

    Note that this technically will not allow 0 to be there (since 0.0001 would be rounded up), so you could just draw from

    ceiling(runif(10000, -1, 10^12))
    

    As Carl Witthoft mentions, numbers that do not fit into the size of an integer will not be integers obviously, so you cannot count on these numbers to be integers. You can still count on them to evaluate to TRUE when compared to the same floating number without decimals though.

提交回复
热议问题