Thursday, February 19, 2015

py24. Exponential Distribution in Python

The exponential distribution, gives probability of events in time, etc, which is usually denoted by x, given a rate of lambda. The Poisson distribution gives the number of events with a rate. Rate and time are reciprocal, so expected value of x is 1/lambda.


The exponential distribution cumulative density function, CDF, is:


P(X<=x) = 1 - exp(-lambda*x)


Three important x values are:.


x = 0. P(X<=0) = 0, as exp(0) = 1, number of probability at time 0 is 0, where the function starts.


x = 1/lambda. P(X<=1/lambda)= 0.632 as exp(-1) = 0.368, that is, we have a little less than 2/3 probability.


x = Infinity. P(X<=Infinity) = 1, as exp(-Infinity) = 0, since probability has to happen in some finite time.


The probability density function is the derivative with respect to x, lambda*exp(-lambda*x).


The function scipy.stats.expon.cdf is used for the exponential CDF. In the call to this function, we have to put the mean value: 1/lambda. Again, since lambda is a reserved word in Python, we used lamb_da in the example.

# ex24.py
from __future__ import print_function, division
import matplotlib.pyplot as plt
import numpy as np
from scipy.stats import expon

N = 1.1
x = np.arange(N+.01,step=.01)

def exp_dis(lamb_da, calc):
    dis_calc = 1 - np.exp(-lamb_da*x)
    dis_R = expon.cdf(x,scale = 1/lamb_da)
    if calc: return dis_calc
    else: return dis_R

c0 = 0.8
plt.plot(x,exp_dis(1, False), color = (0,1-c0,c0))
plt.xlabel('x')
plt.ylabel('p')
plt.title('Exponential Distribution (lambda = 9,7,5,3,1)')
plt.plot(x, [1-np.exp(-1)]*len(x), color = 'red')
for i in 3,5,7,9:
    c0 -= .1
    plt.plot(x,exp_dis(i, False),
         color = (0,1-c0,c0))
plt.show()         
err = exp_dis(9,True)-exp_dis(9,False)
print('err for lambda of 9 =', err.std())
# err for lambda of 9 = 3.03591780425e-17

Output:

No comments:

Post a Comment