11

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?

1
  • 5
    10 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. Commented Dec 17, 2012 at 18:04

3 Answers 3

12

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
...
Sign up to request clarification or add additional context in comments.

4 Comments

Minor nitpick but I think it should be 1 & (s >> x)
@PiotrLopusiewicz: Either way works in that they evaluate to True or False the same, but yours is always 0 or 1 which I guess is a little neater :)
random.randint(0, 2**n-1) does not work for n>63: OverflowError: Python int too large to convert to C long
@QuantMetropolis: Works for me, Python 2.7 and 3.5. Are you sure it's this exact bit of code that gives the error? If so exactly which Python version and implementation are you using?
5

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.

1 Comment

Actually the right way to create an array of 'n' random bits using numpy is: arr = numpy.random.randint(2, size=(n,))
0

Here is a one liner:

import random
[random.randrange(2) for _ in range(10000)]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.