Skip to content

Instantly share code, notes, and snippets.

@nnathan
Created September 13, 2024 07:46
Show Gist options
  • Save nnathan/cb272ac5cfd59c2223b6c5ca2080899c to your computer and use it in GitHub Desktop.
Save nnathan/cb272ac5cfd59c2223b6c5ca2080899c to your computer and use it in GitHub Desktop.
Code demonstrating modulo bias
# Code based on excellent article:
# https://research.kudelskisecurity.com/2020/07/28/the-definitive-guide-to-modulo-bias-and-how-to-avoid-it/
# by Yolan Romailler at Kudelski Security
import pandas
import os
# modulo bias
values = []
while len(values) <= 1000000:
x = int.from_bytes(os.urandom(1), byteorder='little')
values.append(x % 107)
s = pandas.DataFrame({'value':values})
pandas.DataFrame.plot(s).hist(bins=107).get_figure().savefig('modulo-bias.pdf')
# rejection sampling
values = []
while len(values) <= 1000000:
x = int.from_bytes(os.urandom(1), byteorder='little')
if x < 107: values.append(x % 107)
s = pandas.DataFrame({'value':values})
pandas.DataFrame.plot(s).hist(bins=107).get_figure().savefig('rejection-sampling.pdf')
# using large random number (32b)
values = []
while len(values) <= 1000000:
x = int.from_bytes(os.urandom(32), byteorder='little')
values.append(x % 107)
s = pandas.DataFrame({'value':values})
pandas.DataFrame.plot(s).hist(bins=107).get_figure().savefig('large-random.pdf')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment