Skip to content

Commit

Permalink
#65 unbiased_random
Browse files Browse the repository at this point in the history
  • Loading branch information
wojtask committed May 2, 2024
1 parent 14558fa commit bc64729
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 0 deletions.
16 changes: 16 additions & 0 deletions src/solutions/chapter5/section1/exercise3.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
from random import uniform

p = uniform(0, 1)


def unbiased_random():
while True:
x = __biased_random()
y = __biased_random()
if x != y:
break
return x


def __biased_random():
return 1 if uniform(0, 1) <= p else 0
13 changes: 13 additions & 0 deletions test/test_solutions/test_chapter5.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
from hypothesis import strategies as st

from solutions.chapter5.section1.exercise2 import random
from solutions.chapter5.section1.exercise3 import unbiased_random
from test_case import ClrsTestCase
from util import range_of

Expand All @@ -18,3 +19,15 @@ def test_random(self, data):
x = random(a, b)

self.assertIn(x, range_of(a, to=b))

def test_unbiased_random(self):
samples = 1000
count0 = 0
for _ in range_of(1, to=samples):

x = unbiased_random()

self.assertIn(x, range_of(0, to=1))
if x == 0:
count0 += 1
self.assertAlmostEqual(count0 / samples, 0.5, delta=0.1)

0 comments on commit bc64729

Please sign in to comment.