Integration of Logistic distribution in R

Viewed 150

The probability density function of Logistic distribution $f(x) = e^{-x} (1+e^{-x})^{-2}$

LL_cdf <- function(x) ((1+exp(-x))^(-1) # cumulative distribution function of logistic distribution

LL_pdf <- function(x) ( (exp(-x))*(1+exp(-x))^-2 ) # Probability density function (pdf) of logistic distribution

The integration of the pdf of any distribution on its support must be one. We integrate the pdf of logistic distribution on its support $x \in [-\infty,\infty]$ but It gives error message. We mention the the error message in code below. Why the pdf of the logistic distribution does not integrate over its support $x \in [-\infty,\infty]$ in R?

integrate( LL_pdf, lower = -Inf, upper = Inf)$value 

Error in integrate(LL_pdf, lower = -Inf, upper = Inf) : 
  non-finite function value

1 Answers

It has to do with your implementation of the density function as it produces ratios of the type Inf/Inf = NaN for large negative values

> LL_pdf(-1000)
[1] NaN

The implementation of a function should avoid this kind of numerical issues (0/0, Inf/Inf).

A solution is to implement the log density, which is numerically stable, and to return the exponential of the log density, which avoids this kind of issues:

LL_pdf2 <- Vectorize(function(x){
  log.val <- -x -2*log(1+exp(-x))
  return(exp(log.val))
  })  # Probability density function (pdf) of logistic distribution

Then, you obtain,

> LL_pdf2(-1000)
[1] 0
> 
> integrate( LL_pdf2, lower = -Inf, upper = Inf)$value
[1] 1

You can compare these results with those obtained with dlogis

> dlogis(-1000)
[1] 0
> integrate( dlogis, lower = -Inf, upper = Inf)$value
[1] 1
Related