Last active
June 30, 2017 15:46
-
-
Save rvcx/c68c41930ac3c1233a426338331a0710 to your computer and use it in GitHub Desktop.
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 python3 | |
# Simulator for https://fivethirtyeight.com/features/who-steals-the-most-in-a-town-full-of-thieves/ | |
import random | |
import statistics | |
def simulate(k): | |
assets = [100 for i in range(k)] | |
for robber in range(k): | |
victim = random.randrange(k - 1) | |
if victim >= robber: | |
victim += 1 | |
assets[robber] += assets[victim] | |
assets[victim] = 0 | |
return assets | |
def gini(assets): | |
total, lorentz_area = 0, 0 | |
for a in sorted(assets): | |
total += a | |
lorentz_area += total | |
return 1 - 2.0 * lorentz_area / (sum(assets) * len(assets)) | |
def main(): | |
data = [simulate(1000) for i in range(10000)] | |
ginis = [gini(d) for d in data] | |
print("gini: {:4.4} {:4.4} {:4.4}".format(statistics.median(ginis), | |
statistics.mean(ginis), | |
statistics.variance(ginis))) | |
buckets = 75 # bucket together collections of houses for visualization | |
for b in range(buckets): | |
outcomes = [] | |
for d in data: | |
outcomes.extend(d[len(d) // buckets * b : len(d) // buckets * (b + 1)]) | |
print("{:>2} {:4.4} {:4.4} {:4.4}".format(b, | |
statistics.median(outcomes), | |
statistics.mean(outcomes), | |
statistics.variance(outcomes))) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment