Commit 34806263 authored by Tim McNamara's avatar Tim McNamara

Add generate-a-random-range.md

parent 21e44729
Let's say that we're presented with a random number generator that only produces
random bytes.. but what we really want is a random number between `[n,m]`.
- Treat bytes as an unsigned integer, then divide by the max that integer could
generate. This will produce a proportion.
- Multiply the difference in the range by the proportion
- Add start to the result of the previous operation
First, assuming that can get the proportion for free.
```python
import random
def rand_range(start, end):
diff = end - start
proportion = random.random()
return start + (proportion * diff)
```
When we need to generate the proportion ourselves, there is more work to do:
```python
def random_bytes(n_bytes, source='/dev/urandom'):
with open(source, 'rb') as f:
entropy = f.read(n_bytes)
return entropy
def rand_from_bytes(n_bytes):
assert n_bytes in {1, 2, 4, 8}
entropy = random_bytes(n_bytes)
typecode = {1: 'B', 2: 'H', 4: 'I', 8: 'Q'}[n_bytes]
r, = struct.unpack(typecode, entropy)
return r / (1 << 8*n_bytes)
def rand_range(start, end):
diff = end - start
proportion = rand_from_bytes()
return start + (proportion * diff)
```
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment