Reputation: 442
I need to generate numbers on a positive given interval (a,b) distributed following an exponential distribution. Using the Inverse CDF Method, I made a generator of a number exponentialy distributed. But, of course, this number is a positive number and I want it to be on the given interval. What should I do to only generate on the interval?
The code to generate a number exponentially distributed using the inverse cdf method is, in Python
u = random.uniform(0,1)
return (-1/L)*math.log(u)
where L is a given positive parameter.
Thanks in advance
Upvotes: 4
Views: 1046
Reputation: 968
The probability of an outcome x would normally be L exp(-Lx). However, when we are restricted to [a,b], the probability of x in [a,b] is scaled up by 1/the fraction of the CDF that occurs between a and b: integral from a to b(L exp(-Lt)dt) = -(exp(-Lb) - exp(-La)).
Therefore, the pdf at x is
L exp(-Lx))/(exp(-La) - exp(-Lb),
giving a cdf at x of
integral from a to x[ L exp(-Lt)/(exp(-La) - exp(-Lb))dt]
= [-exp(-Lx) + exp(-La)]/[exp(-La) - exp(-Lb)] = u
Now invert:
exp(-Lx) = exp(-La) - u[exp(-La) - exp(-Lb)]
-Lx = -La + log( 1 - u[1 - exp(-Lb)/exp(-La)])
x = a + (-1/L) log( 1 - u[1 - exp(-Lb)/exp(-La)])
giving code:
u = random.uniform(0,1)
return a + (-1/L)*math.log( 1 - u*(1 - math.exp(-L*b)/math.exp(-L*a)) )
be aware: for large L or a, math.exp(-L*a)
will round to 0, leading to ZeroDivisionError
.
Upvotes: 2