Skip to content

Instantly share code, notes, and snippets.

@anilkeshwani
Created July 11, 2025 12:26
Show Gist options
  • Select an option

  • Save anilkeshwani/116b027063aa62d31815d721e831987e to your computer and use it in GitHub Desktop.

Select an option

Save anilkeshwani/116b027063aa62d31815d721e831987e to your computer and use it in GitHub Desktop.
import random
import matplotlib.pyplot as plt
def choose_from(size: int) -> int:
start, end = 0, size
dst = size
while dst > 1:
if random.getrandbits(1):
start += dst // 2 # choose rhs
else:
end -= dst // 2 # choose lhs
dst = end - start
return start
N = 100_000
n = 512
assert n > 0 and (n & (n - 1) == 0), "range must be positive power of 2"
rand_output = [choose_from(n) for i in range(N)]
# Plot histogram
plt.figure(figsize=(12, 5))
plt.hist(rand_output, bins=n, range=(0, n), edgecolor='black', density=False)
plt.xlabel('Chosen number')
plt.ylabel('Frequency')
plt.title(f'Histogram of Random Integer Choices over {N} Trials (Range = {n})')
plt.grid(True, axis='y', linestyle='--', alpha=0.7)
plt.tight_layout()
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment