I want to run a simulation that uses as parameter a value generated from a triangular probability distribution with lower limit A, mode B and and upper limit C. How can I generate this value in Python? Is there something as simple as expovariate(lambda) (from random) for this distribution or do I have to code this thing?
views:
385answers:
3
+5
A:
If you download the NumPy package, it has a function numpy.random.triangular(left, mode, right[, size]) that does exactly what you are looking for.
erik
2009-05-03 00:30:52
A:
Let's say that your distribution wasn't handled by NumPy or the Python Standard Library.
In situations where performance is not very important, rejection sampling is a useful hack for getting draws from a distribution you don't have using one you do have.
For your triangular distribution, you could do something like
from random import random, uniform
def random_triangular(low, high, mode):
while True:
proposal = uniform(low, high)
if proposal < mode:
acceptance_prob = (proposal - low) / (mode - low)
else:
acceptance_prob = (high - proposal) / (high - mode)
if random() < acceptance_prob: break
return proposal
You can plot some samples
pylab.hist([random_triangular(1, 6, 5) for t in range(10000)])
to make sure that everything looks okay.
othercriteria
2009-05-28 20:49:34