#' (Weighted) MLE of Rayleigh Distribution
#'
#' Rayleigh distribution is characterized by the following probability density function,
#' \deqn{f(x;\sigma) = \frac{x}{\sigma^2} \exp( -x^2 / (2\sigma^2))}
#' where the domain is nonnegative real number \eqn{x \in [0,\infty)} with scale parameter \eqn{\sigma > 0}.
#'
#' @param x a length-\eqn{n} vector of nonnegative real numbers.
#' @param weight a length-\eqn{n} weight vector. If set as \code{NULL}, it gives an equal weight, leading to standard MLE.
#'
#' @return a named list containing (weighted) MLE of \describe{
#' \item{sigma}{scale parameter \eqn{\sigma}.}
#' }
#'
#' @examples
#' # generate data from exponential distribution with lambda=1
#' x = stats::rexp(100, rate=1)
#'
#' # fit unweighted
#' Rayleigh(x)
#'
#' \dontrun{
#' # put random weights to see effect of weights
#' niter = 500
#' ndata = 200
#'
#' # generate data and fit unweighted MLE
#' x = stats::rexp(ndata, rate=1)
#' xmle = Rayleigh(x)
#'
#' # iterate
#' vec.sigma = rep(0,niter)
#' for (i in 1:niter){
#' # random weight
#' ww = abs(stats::rnorm(ndata))
#'
#' MLE = Rayleigh(x, weight=ww)
#' vec.sigma[i] = MLE$sigma
#' if ((i%%10) == 0){
#' print(paste0(" iteration ",i,"/",niter," complete.."))
#' }
#' }
#'
#' # distribution of weighted estimates + standard MLE
#' opar <- par(no.readonly=TRUE)
#' hist(vec.sigma, main="scale 'sigma'")
#' abline(v=xmle$sigma, lwd=3, col="red")
#' par(opar)
#' }
#'
#' @author Kisung You
#' @export
Rayleigh <- function(x, weight=NULL){
#############################################
# Preprocessing
x = handle_cts_nonneg("BetaPrime", x) # nonnegative real numbers
nx = length(x)
weight = handle_weight("BetaPrime", weight, nx)
maceps = 10*.Machine$double.eps
#############################################
# Optimize : R's optimize
fopt.Rayleigh <- function(sig){
# log-likelihood
loglkd = -((x^2)/(2*(sig^2))) + log(x) - 2*log(sig)
# return
return(sum(loglkd*weight))
}
sol = stats::optimize(fopt.Rayleigh, lower=maceps, upper=1e+5, maximum = TRUE)
#############################################
# Return
output = list()
output$sigma = as.double(sol$maximum)
return(output)
}
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.