Last active
April 7, 2024 14:44
-
-
Save StuartGordonReid/3b7926ab5c9a3319bfc2 to your computer and use it in GitHub Desktop.
Python implementation of the Monobit test for randomness
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
instead of:
You may do this for better performance: