Last active
July 26, 2018 23:16
-
-
Save YuvalFilmus/b0552be98067acec49ddaa731f2b8b74 to your computer and use it in GitHub Desktop.
Generating uniform random bits for iid binary source
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class bitstream: | |
def __init__(self, emit): | |
self.emit = emit | |
self.bits = [] | |
self.daughters = [None, None] | |
def daughter(self, num): | |
if self.daughters[num] is None: | |
self.daughters[num] = bitstream(self.emit) | |
return self.daughters[num] | |
def send(self, bit): | |
self.bits.append(bit) | |
if len(self.bits) < 2: | |
return | |
a, b = self.bits[0], self.bits[1] | |
self.bits = [] | |
if a == b: | |
self.daughter(0).send(a) | |
self.daughter(1).send(0) | |
else: | |
self.emit(a) | |
self.daughter(1).send(1) | |
import random | |
def test(p, n, seed = None): | |
output = [] | |
random.seed(seed) | |
bs = bitstream(lambda x: output.append(x)) | |
for _ in xrange(n): | |
bs.send(int(random.random() < p)) | |
return output |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment