Skip to content

Instantly share code, notes, and snippets.

@StuartGordonReid
Last active April 7, 2024 14:44
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save StuartGordonReid/3b7926ab5c9a3319bfc2 to your computer and use it in GitHub Desktop.
Save StuartGordonReid/3b7926ab5c9a3319bfc2 to your computer and use it in GitHub Desktop.
Python implementation of the Monobit test for randomness
def monobit(self, bin_data: str):
"""
Note that this description is taken from the NIST documentation [1]
[1] http://csrc.nist.gov/publications/nistpubs/800-22-rev1a/SP800-22rev1a.pdf
The focus of this test is the proportion of zeros and ones for the entire sequence. The purpose of this test is
to determine whether the number of ones and zeros in a sequence are approximately the same as would be expected
for a truly random sequence. This test assesses the closeness of the fraction of ones to 1/2, that is the number
of ones and zeros ina sequence should be about the same. All subsequent tests depend on this test.
:param bin_data: a binary string
:return: the p-value from the test
"""
count = 0
# If the char is 0 minus 1, else add 1
for char in bin_data:
if char == '0':
count -= 1
else:
count += 1
# Calculate the p value
sobs = count / math.sqrt(len(bin_data))
p_val = spc.erfc(math.fabs(sobs) / math.sqrt(2))
return p_val
@JimChr-R4GN4R
Copy link

instead of:

count = 0
    # If the char is 0 minus 1, else add 1
    for char in bin_data:
        if char == '0':
            count -= 1
        else:
            count += 1

You may do this for better performance:

zeros = bin_data.count('0')
count = zeros - (len(bin_data) - zeros)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment