Generating random numbers with a given probability density function

后端 未结 2 1135
有刺的猬
有刺的猬 2021-01-05 11:32

I want to specify the probability density function of a distribution and then pick up N random numbers from that distribution in Python. How do I go about doing that?

2条回答
  •  旧时难觅i
    2021-01-05 12:08

    This is my function to retrieve a single random number distributed according to the given probability density function. I used a Monte-Carlo like approach. Of course n random numbers can be generated by calling this function n times.

        """
        Draws a random number from given probability density function.
    
        Parameters
        ----------
            pdf       -- the function pointer to a probability density function of form P = pdf(x)
            interval  -- the resulting random number is restricted to this interval
            pdfmax    -- the maximum of the probability density function
            integers  -- boolean, indicating if the result is desired as integer
            max_iterations -- maximum number of 'tries' to find a combination of random numbers (rand_x, rand_y) located below the function value calc_y = pdf(rand_x).
    
        returns a single random number according the pdf distribution.
        """
        def draw_random_number_from_pdf(pdf, interval, pdfmax = 1, integers = False, max_iterations = 10000):
            for i in range(max_iterations):
                if integers == True:
                    rand_x = np.random.randint(interval[0], interval[1])
                else:
                    rand_x = (interval[1] - interval[0]) * np.random.random(1) + interval[0] #(b - a) * random_sample() + a
    
                rand_y = pdfmax * np.random.random(1) 
                calc_y = pdf(rand_x)
    
                if(rand_y <= calc_y ):
                    return rand_x
    
            raise Exception("Could not find a matching random number within pdf in " + max_iterations + " iterations.")
    

    In my opinion this solution is performing better than other solutions if you do not have to retrieve a very large number of random variables. Another benefit is that you only need the PDF and avoid calculating the CDF, inverse CDF or weights.

提交回复
热议问题