Generate 10,000 bits of random sequence

Is there a more efficient way to generate a random 10 kbit (10,000 bit) binary sequence in Python than adding 0 and 1 to the loop?

+7
source share
2 answers

If you want a random binary sequence, then it's probably the quickest way to create a random integer in the corresponding range:

import random s = random.randint(0, 2**10000 - 1) 

After that, it really depends on what you want to do with your binary sequence. You can request individual bits using bitwise operations:

 s & (1 << x) # is bit x set? 

or you can use a library, such as bitarray or bitstring , if you want to check, set up a section, etc. simpler:

 from bitstring import BitArray b = BitArray(uint=s, length=10000) p, = b.find('0b000000') if b[99]: b[100] = False ... 
+10
source

The numpy package has a "random" subpackage that can create arrays of random numbers.

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

If you need an array of "n" random bits, you can use

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

... but depending on what you do with them, it may be more efficient to use, for example.

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

to get an array of numbers "n", each of which contains 16 random bits; then

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

turns this into a string of 2 * n characters containing the same random bits.

+3
source

All Articles