Skip to content

Instantly share code, notes, and snippets.

@EHDEV
Created March 25, 2015 02:03
Show Gist options
  • Save EHDEV/7995be21ca6ae51a205b to your computer and use it in GitHub Desktop.
Save EHDEV/7995be21ca6ae51a205b to your computer and use it in GitHub Desktop.
Inverse Transform Random Sampler
def rand_sampler(self, n, prob, u):
"""
Generates a random sample of k numbers according to the discrete probability distribution
n: sample size
pro: probability distribution
"""
cdf = []
np.random.seed(100)
for k in range(0, len(prob)):
cdf.append(sum([prob[k] for k in range(0, k + 1)]))
# u = np.random.sample(n)
rds = []
for j in range(0, len(cdf)):
if j == 0:
tmp = np.where(u <= cdf[j])[0]
rds += np.repeat(j, len(tmp)).tolist()
else:
print j
tmp = np.where(np.logical_and(u <= cdf[j], u > cdf[j - 1]))[0]
rds += np.repeat(j, len(tmp)).tolist()
return rds
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment