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?
-
510 kBit as in "ten thousand bits"? That wouldn't normally be called a "signal". Are you talking about a waveform? And/or a continuous signal of 10,000 bits per second or something? Please clarify, preferably a lot.unwind– unwind2012-12-17 18:04:19 +00:00Commented Dec 17, 2012 at 18:04
3 Answers
If you want a random binary sequence then it's probably quickest just to generate a random integer in the appropriate range:
import random
s = random.randint(0, 2**10000 - 1)
After this it really depends on what you want to do with your binary sequence. You can query individual bits using bitwise operations:
s & (1 << x) # is bit x set?
or you could use a library like bitarray or bitstring if you want to make checking, setting slicing etc. easier:
from bitstring import BitArray
b = BitArray(uint=s, length=10000)
p, = b.find('0b000000')
if b[99]:
b[100] = False
...
4 Comments
OverflowError: Python int too large to convert to C longThe 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.