% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/logspace.utils.R
\name{logspace.utils}
\alias{logspace.utils}
\alias{log_sum_exp}
\alias{log_mean_exp}
\alias{lweighted.mean}
\alias{lweighted.var}
\title{Utilities for performing calculations on logarithmic scale.}
\usage{
log_sum_exp(logx, use_ldouble = FALSE)

log_mean_exp(logx, use_ldouble = FALSE)

lweighted.mean(x, logw)

lweighted.var(x, logw)
}
\arguments{
\item{logx}{Numeric vector of \eqn{\log(x)}, the natural logarithms of the
values to be summed or averaged.}

\item{use_ldouble}{Whether to use \code{long double} precision in the
calculation. If \code{TRUE}, 's C built-in \code{logspace_sum()} is used. If
\code{FALSE}, the package's own implementation based on it is used, using
\code{double} precision, which is (on most systems) several times faster, at
the cost of precision.}

\item{x}{Numeric vector of \eqn{x}, the (raw) values to be summed
or averaged. For \code{lweighted.mean} and \code{lweighted.var},
\code{x} may also be a matrix, in which case the weighted mean
will be computed for each column of \code{x} and the weighted
variance-covariance matrix of the columns of \code{x} will be
returned, respectively.}

\item{logw}{Numeric vector of \eqn{\log(w)}, the natural logarithms of the
weights.}
}
\value{
The functions return the equivalents of the following R expressions,
but faster and with less loss of precision: \describe{
\item{\code{log_sum_exp(logx)}}{\code{log(sum(exp(logx)))}}
\item{\code{log_mean_exp(logx)}}{\code{log(mean(exp(logx)))}}
\item{\code{lweighted.mean(x,logw)}}{\code{sum(x*exp(logw))/sum(exp(logw))} for \code{x} scalar and
\code{colSums(x*exp(logw))/sum(exp(logw))} for \code{x} matrix}
\item{\code{lweighted.var(x,logw)}}{\code{crossprod(x*exp(logw/2))/sum(exp(logw))}} }
}
\description{
A small suite of functions to compute sums, means, and weighted means on
logarithmic scale, minimizing loss of precision.
}
\examples{

logx <- rnorm(1000)
stopifnot(all.equal(log(sum(exp(logx))), log_sum_exp(logx)))
stopifnot(all.equal(log(mean(exp(logx))), log_mean_exp(logx)))

x <- rnorm(1000)
logw <- rnorm(1000)
stopifnot(all.equal(m <- sum(x*exp(logw))/sum(exp(logw)),lweighted.mean(x, logw)))
stopifnot(all.equal(sum((x-m)^2*exp(logw))/sum(exp(logw)),
                    lweighted.var(x, logw), check.attributes=FALSE))

x <- cbind(x, rnorm(1000))
stopifnot(all.equal(m <- colSums(x*exp(logw))/sum(exp(logw)),
                    lweighted.mean(x, logw), check.attributes=FALSE))
stopifnot(all.equal(crossprod(t(t(x)-m)*exp(logw/2))/sum(exp(logw)),
                    lweighted.var(x, logw), check.attributes=FALSE))
}
\author{
Pavel N. Krivitsky
}
\keyword{arith}
