Skip to content Skip to sidebar Skip to footer

Generate A Random Number According To A Specific Distribution With A Function

I am trying to generate a random number in Python according to a precise distribution that I define with a function f (theta) = 1 + alpha*cos(theta)²; the variable alpha is a cons

Solution 1:

Assuming f is proportional to a probability density function (PDF) you can use the rejection sampling method: Draw a number in a box until the box falls within the PDF. It works for any bounded PDF with a finite domain, as long as you know what the domain and bound are (the bound is the maximum value of f in the domain). In this case, the bound is 1 + alpha and the algorithm works as follows:

import math
import random

def sample(alpha):
    mn=0 # Lowest value of domain
    mx=math.pi # Highest value of domain
    bound=1+alpha # Upper bound of PDF value
    while True:
       # Choose an X inside the desired sampling domain.
       x=random.uniform(mn,mx)
       # Choose a Y between 0 and the maximum PDF value.
       y=random.uniform(0,bound)
       # Calculate PDF
       pdf=1+alpha*math.cos(x)**2
       # Does (x,y) fall in the PDF?
       if y<pdf:
           # Yes, so return x
           return x
       # No, so loop

Post a Comment for "Generate A Random Number According To A Specific Distribution With A Function"