Skip to content

Instantly share code, notes, and snippets.

@sdstrowes
Created June 14, 2020 11:10
Show Gist options
  • Save sdstrowes/68226a5f9ad98892cf2299307db2d78c to your computer and use it in GitHub Desktop.
Save sdstrowes/68226a5f9ad98892cf2299307db2d78c to your computer and use it in GitHub Desktop.
visualise random vs sequential bit allocations
import random
import numpy as np
from matplotlib import pyplot as plt
fixed_bits = 32
variable_bits = 32
bitlen = fixed_bits + variable_bits
iterations = 2048
def longest_match(old, new):
old = bin(old)[2:]
new = bin(new)[2:]
for i in range(0, len(old)):
if old[i] != new[i]:
return i+1
return -1
def plot(counts, name, subheading):
a = np.array(counts)
fig = plt.figure(figsize=[7,5])
ax = plt.subplot(111)
plt.xticks(np.arange(0, bitlen+1, step=8))
ax.set_xlabel('longest bitmatch')
ax.set_ylabel('frequency')
ax.set_title(name + ": " + subheading)
ax.bar(range(0,len(counts)),counts)
plt.savefig(name + ".png")
# Set a string of 1s
network = (2**bitlen)-1
print("1 ",network,bin(network))
# Squash the variable part to zeroes
# Acts like a netmask
network = network - ((2 ** variable_bits)-1)
print("2 ",network,bin(network))
# count into these bins
# use for histogram later
histo_counts = [0] * bitlen
old_ip = network
for i in range(1, iterations):
r = random.randrange(0,2**variable_bits)
new_ip = network | r
n = longest_match(old_ip, new_ip)
print(n, hex(old_ip), hex(new_ip))
histo_counts[n-1] += 1
old_ip = new_ip
plot(histo_counts, "random", str(fixed_bits) + " fixed + " + str(variable_bits) + " bits variable, " + str(iterations) + " iterations")
# reset counts
histo_counts = [0] * bitlen
old_ip = network
for i in range(1, iterations):
new_ip = old_ip + 1
n = longest_match(old_ip, new_ip)
print(n, hex(old_ip), hex(new_ip))
histo_counts[n-1] += 1
old_ip = new_ip
plot(histo_counts, "linear", str(fixed_bits) + "fixed + " + str(variable_bits) + " bits variable, " + str(iterations) + " iterations")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment