Created
February 26, 2013 23:41
-
-
Save rafalio/5043438 to your computer and use it in GitHub Desktop.
Random number proportional to its value.
This file contains hidden or 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 prop_random(r): | |
S = sum(r) | |
i = -1 | |
rand = random.randint(1,S) | |
while(rand > 0): | |
i = i + 1 | |
rand = rand - r[i] | |
return r[i] | |
mm = dict() # Stores simulation results | |
N = 100000 | |
for i in range(N): | |
o = prop_random([5,2,1,4,3]) | |
if(o in mm): | |
mm[o] += 1 | |
else: | |
mm[o] = 1 | |
for a,b in mm.iteritems(): | |
print a, " --> ", b/float(N) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment