Created
October 12, 2020 06:15
-
-
Save rt121212121/0c60f852e3cdfd4d164aa27b30a15248 to your computer and use it in GitHub Desktop.
Simple script implementing nchain benford's law distribution example
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
# https://nchain.com/2019/10/22/benfords-wallet/ | |
from collections import defaultdict | |
import random | |
def f(v, n): | |
l = [] | |
for i in range(n-1): | |
l.append(random.randint(1, v)) | |
l.append(v) | |
return l | |
def g(l_in): | |
l = sorted(l_in) | |
last_value = 0 | |
l_out = [] | |
for current_value in l: | |
interval = current_value - last_value | |
l_out.append(interval) | |
last_value = current_value | |
return l_out | |
def count_leading_digits(l_in): | |
d = defaultdict(int) | |
for value in l_in: | |
digit = int(str(value)[0]) | |
d[digit] += 1 | |
digit_counts = list(d.items()) | |
digit_counts.sort(key=lambda v: -v[1]) | |
return digit_counts | |
# Sample run in interpreter: | |
# | |
# >>> l_g = f(45110034324222, 10000) | |
# >>> g_g = g(l_g) | |
# >>> count_leading_digits(g_g) | |
# [(1, 2888), (2, 1538), (3, 1277), (4, 1008), (5, 922), (6, 729), (7, 649), (8, 533), (9, 456)] | |
# | |
# Expected distribution: | |
# [ 1, 2, 3, 4, 5, 6, 7, 8, 9] | |
# [30.1, 17.6, 12.5, 9.7, 7.9, 6.7, 5.8, 5.1, 4.6] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment