Random decimal numbers from uniform binary numbers

Let’s generate a list of 0s and 1s first, I would like each a 50% chance for each ┬ánumber to come up so the binary list would be uniform.

Create a random binary file

import os

with open('output_file', 'wb') as fout:
    fout.write(os.urandom(1024))

def bits(f):
    bytes = (ord(b) for b in f.read())
    for b in bytes:
        for i in xrange(8):
            yield (b >> i) & 1

for b in bits(open('output_file', 'r')):
    print b

Now let’s check if these are uniformly distributed. First let’s check the number of 0s and 1s, there should be approximately the same number of both.

one ,zero = 0,0
binaryList = []
for b in bits(open('output_file', 'r')):
    binaryList.append(b)
    if b == 1:
        one=one+1
    if b == 0:
        zero=zero+1

print "In the entire set"
print "ones =",one
print "zeros =",zero

In the entire set
ones = 4125
zeros = 4067

This seems ok. We can also check if the they are equally distributed in some arbitrary subset.

import os

with open('output_file', 'wb') as fout:
    fout.write(os.urandom(1024))

def bits(f):
    bytes = (ord(b) for b in f.read())
    for b in bytes:
        for i in xrange(8):
            yield (b >> i) & 1

one ,zero = 0,0
binaryList = []
for b in bits(open('output_file', 'r')):
    binaryList.append(b)
    if b == 1:
        one=one+1
    if b == 0:
        zero=zero+1

print "In the entire set"
print "ones =",one
print "zeros =",zero


one ,zero = 0,0
for b in binaryList[:len(binaryList)/2]:
    if b == 1:
        one=one+1
    if b == 0:
        zero=zero+1

print "In half of the entire set"
print "ones =",one
print "zeros =",zero

one ,zero = 0,0
for b in binaryList[:len(binaryList)/4]:
    if b == 1:
        one=one+1
    if b == 0:
        zero=zero+1

print "In a quarter of the entire set"
print "ones =",one
print "zeros =",zero

In the entire set
ones = 4125
zeros = 4067
In half of the entire set
ones = 2072
zeros = 2024
In a quarter of the entire set
ones = 1038
zeros = 1010

This still looks good. Now I would like to make decimal numbers out of these.

Advertisements
Standard