Thursday, February 19, 2015

R24. Exponential Distribution in R

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 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 pexp is used for the exponential CDF.

# ex24.R
N <- 1.1
x <- seq(0,N,.01)

exp.dis <- function(lambda, calc) {
  dis.calc <- 1 - exp(-lambda*x)
  dis.R <- pexp(x,lambda)
  if (calc) {
    r <- dis.calc
  } else {
    r <- dis.R
  }
  r
}

c0 <- 0.8
plot(x,exp.dis(1, FALSE), col = rgb(0,1-c0,c0),
     type = 'l', xlab = 'x', ylab = 'p',
     main = "Exponential Distribution (lambda = 9,7,5,3,1)")
abline(h = 1 - exp(-1), col = 'red')
for (i in seq(3,9,2)) {
  c0 <- c0-.1
  pr <- (i-1)/2 + 1
  points(x,exp.dis(i, TRUE), 
         col = rgb(0,1-c0,c0), type = 'l')
}
err <- exp.dis(9,TRUE)-exp.dis(9,FALSE)
cat('err for lambda of 9 =', sd(err))
# err for lambda of 9 = 3.462564e-17

Output:

No comments:

Post a Comment