0

Is there build in numpy funciton to return index idx from one dimensional array r with probability r[i]. All r[i] non negative and sums to one.

2 Answers 2

1

Almost built in:

# setup (do this once)
cs = r.cumsum()

# get a random value with probability r[i]
rn = np.random.uniform()
idx = cs.searchsorted(rn)
Sign up to request clarification or add additional context in comments.

Comments

0

scipy.stats can help, even if it is not in NumPy as requested:

import scipy.stats
r = [.1,.8,.1]
x = range(len(r))
mydist = scipy.stats.rv_discrete(values=(x,r), name='mydist')
print mydist.rvs(size=20)
# array([1, 1, 0, 0, 1, 1, 2, 2, 1, 1, 2, 1, 2, 1, 1, 1, 1, 1, 1, 1])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.