Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Random values from a PERT distribution in Python

I'd like to generate in Python 10,000 random values from a PERT distribution that has the following parameters low=6898.5, peak= 7338.93, high=7705.87

How can I do that?

like image 620
turaran32 Avatar asked Mar 17 '26 20:03

turaran32


2 Answers

If you just want to use the standard library, you could do something like:

from random import betavariate

def pert(a, b, c, *, lamb=4):
    r = c - a
    alpha = 1 + lamb * (b - a) / r
    beta = 1 + lamb * (c - b) / r
    return a + betavariate(alpha, beta) * r

arr = [pert(6898.5, 7338.93, 7705.87) for _ in range(10_000)]

Using Numpy is mostly the same:

import numpy as np

def pert(a, b, c, *, size=1, lamb=4):
    r = c - a
    alpha = 1 + lamb * (b - a) / r
    beta = 1 + lamb * (c - b) / r
    return a + np.random.beta(alpha, beta, size=size) * r

arr = pert(6898.5, 7338.93, 7705.87, size=10_000)

but is about 20 times faster (20ms vs 0.8ms).

Either of these can be used to produce similar plots to Severin, e.g.:

KDE via Seaborn

like image 116
Sam Mason Avatar answered Mar 20 '26 08:03

Sam Mason


using pertdist from PyPi, Python 3.9 Win10 x64

Code

from pert import PERT
import seaborn as sns

low=6898.5
peak=7338.93
high=7705.87

pert = PERT(low, peak, high)
sns.kdeplot(pert.rvs(100000))

produced graph below

enter image description here

like image 35
Severin Pappadeux Avatar answered Mar 20 '26 08:03

Severin Pappadeux



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!