kazi ahad
kazi ahad

Reputation: 19

Random number generator from a given distribution function

I am completely new in programming. I have density function which have two range. How can i get random function according to this function. The probability density function for the last return time is:

      (1/sqrt(2*pi*std**2))*exp(-(x+24-µ2)**2/2*std**2)   ,   0 < x ≤ µ2 − 12
f(x) =
       (1/sqrt(2*pi*std**2))*exp(-(x-µ2)**2/2*std**2) ,  µ2 − 12 < x ≤ 24
                          

std=3.4,µ2=17.6

After finding for couple hours i get this answers 1.get random number from 0to 1 2.calculate cdf 3.calculate inverse cdf 4.get random number

But i dont know how i can implement this in python.

Upvotes: 1

Views: 287

Answers (1)

Tirth Patel
Tirth Patel

Reputation: 1905

You can create your own distribution using scipy.stats.rv_continuous as the base class. This class has fast default implementations of CDF, random number generator, SF, ISF, ect given the PDF of the distribution. You can implement your own distribution using something like:

import numpy as np
from numpy import exp
from scipy.stats import rv_continuous

class my_distribution_gen(rv_continuous):
    def _logpdf(self, x, mu, std):
        # code the log of your pdf function here
        result = # here goes your equation
        return result

    def _pdf(self, x, mu, std):
        return exp(self._logpdf(x, mu, std))

my_distribution = my_distribution_gen(name='my_distribution')

Once you have the above class ready, you can enjoy the default implementations by calling methods like rvs, cdf, etc.

mu, std = 0, 1
rvs = my_distribution.rvs(mu, std)

Upvotes: 1

Related Questions