Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating a 10000 bit random sequence

Tags:

python

binary

Is there a more efficient way to generate a 10 kBit (10,000 bits) random binary sequence in Python than appending 0s and 1s in a loop?

like image 639
Big Puncho Avatar asked Dec 17 '12 17:12

Big Puncho


1 Answers

The numpy package has a subpackage 'random' which can produce arrays of random numbers.

http://docs.scipy.org/doc/numpy/reference/routines.random.html

If you want an array of 'n' random bits, you can use

arr = numpy.random.randint(2, size=(n,))

... but depending on what you are doing with them, it may be more efficient to use e.g.

arr = numpy.random.randint(0x10000, size=(n,))

to get an array of 'n' numbers, each with 16 random bits; then

rstring = arr.astype(numpy.uint16).tostring()

turns that into a string of 2*n chars, containing the same random bits.

like image 73
greggo Avatar answered Sep 25 '22 04:09

greggo