Skip to content

Instantly share code, notes, and snippets.

@ZhanruiLiang
Created June 10, 2015 06:56
Show Gist options
  • Save ZhanruiLiang/8f800d0db780cd45ba12 to your computer and use it in GitHub Desktop.
Save ZhanruiLiang/8f800d0db780cd45ba12 to your computer and use it in GitHub Desktop.
Distribution of generated numbers by a given total sum
from matplotlib import pyplot as plt
def validate(func, s=100, n=5, trails=100000):
counts = [0] * (s + 1)
for _ in xrange(trails):
for x in func(s, n):
counts[x] += 1
plt.plot(range(s + 1), counts)
plt.show()
import random
def rescale_gen(s, n):
while True:
xs = [random.random() for _ in xrange(n)]
s1 = sum(xs)
xs = [int(x * s / s1 + .5) for x in xs]
xs[0] = s - sum(xs[1:])
if xs[0] >= 0:
break
return xs
def sort_gen(s, n):
seps = [random.randint(0, s) for _ in xrange(n - 1)]
seps.sort()
seps.append(s)
seps.append(0)
xs = [seps[i] - seps[i - 1] for i in xrange(n)]
return xs
# validate(rescale_gen)
validate(sort_gen)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment