Created
October 20, 2016 00:10
-
-
Save nocarryr/5c10c8f80d6a5c2df9995133ee161059 to your computer and use it in GitHub Desktop.
Benford's Law
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
#! /usr/bin/env python | |
import argparse | |
def get_first_digit(i): | |
return int(str(i)[0]) | |
def run(iterations): | |
i = 0 | |
n = 1 | |
digit_counts = {} | |
while i <= iterations: | |
d = get_first_digit(n) | |
if d not in digit_counts: | |
digit_counts[d] = 1 | |
else: | |
digit_counts[d] += 1 | |
n *= 2 | |
i += 1 | |
return digit_counts | |
def plot(digit_counts): | |
import matplotlib.pyplot as plt | |
x = sorted(digit_counts) | |
y = [digit_counts[k] for k in x] | |
plt.plot(x, y) | |
plt.show() | |
if __name__ == '__main__': | |
p = argparse.ArgumentParser() | |
p.add_argument('iterations', type=int, default=1000) | |
args = p.parse_args() | |
digit_counts = run(args.iterations) | |
try: | |
plot(digit_counts) | |
except ImportError: | |
print(digit_counts) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment