Skip to content

Instantly share code, notes, and snippets.

@laserson
Created December 14, 2010 20:33
Show Gist options
  • Select an option

  • Save laserson/741050 to your computer and use it in GitHub Desktop.

Select an option

Save laserson/741050 to your computer and use it in GitHub Desktop.
multinomial sample generator
import numpy as np
def multinomial_sample(n,p):
"""Return sample variates from multinomial.
In contrast with `numpy`'s multinomial sampler, this will return the actual
samples, rather than the summed results. In other words, the result of
`numpy`'s sampler is the same length as `p`, while the result of this
sampler is of length `n`.
`n` - number of experiments
`p` - vector of parameters; must sum to 1
"""
if sum(p) != 1.: raise ValueError, "p must sum to 1"
uniform_sample = np.random.uniform(size=n)
p_cum = np.cumsum(p)
return np.searchsorted(p_cum,uniform_sample,side='right')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment