Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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) 

But I get following error message:

Error in 0:1000000000000 : result would be too long a vector 

Is there a more memory efficient method that doesn't have to put 10^12 integers in a vector just to get a sample of size 10000? If not, is there a way to increase the max size of the vector? I'm working on a 64bit OS with 12GB of free RAM.

like image 301
user1775213 Avatar asked Nov 07 '13 12:11

user1775213


People also ask

How do you generate a random number from within a range?

Method 1: Using Math. random() function is used to return a floating-point pseudo-random number between range [0,1) , 0 (inclusive) and 1 (exclusive). This random number can then be scaled according to the desired range.

How do you generate a random number from 0 to 10 in Python?

Use randint() Generate random integer randint() function to get a random integer number from the inclusive range. For example, random. randint(0, 10) will return a random number from [0, 1, 2, 3, 4, 5, 6, 7, 8 ,9, 10].

Which command is used to get a random float number within the range 10 to 20?

uniform() to get a random float number within a range. The random. uniform() function returns a random floating-point number between a given range in Python.


1 Answers

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.

like image 55
PascalVKooten Avatar answered Nov 03 '22 20:11

PascalVKooten