Skip to content

Instantly share code, notes, and snippets.

@erikbern
Last active August 29, 2015 14:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save erikbern/fc05e8cccd64dccde630 to your computer and use it in GitHub Desktop.
Save erikbern/fc05e8cccd64dccde630 to your computer and use it in GitHub Desktop.
Generate Dirichlet distribution
import random, time
import pylab, numpy
def method1(n):
s = 1.0
r = []
for i in xrange(n):
t = s * (1 - random.random() ** (1.0 / (n - i)))
s -= t
r.append(t)
return r
def method1_recursive(n, s=1.0):
if n == 0:
return []
else:
t = s * (1 - random.random() ** (1.0 / n))
return [t] + method1_recursive(n-1, s-t)
def method2(n):
d = [random.random() for i in xrange(n)]
d.sort()
d.append(1.0)
return [d[i+1] - d[i] for i in xrange(n)]
n = 3
for method in [method1, method1_recursive, method2]:
n_iters = 100
t0 = time.time()
dist = []
for iter in xrange(n_iters):
dist += method(n)
dist.sort()
xs = numpy.linspace(1.0 / len(dist), 1.0, num=len(dist))
pylab.plot(dist, xs)
print method, time.time() - t0
pylab.show()
Erik-Bernhard
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment