Learn R Programming

DPQ (version 0.5-3)

logspace.add: Logspace Arithmetix -- Addition and Subtraction

Description

Compute the log(arithm) of a sum (or difference) from the log of terms without causing overflows and without throwing away large handfuls of accuracy.

logspace.add(lx, ly):=

$$\log (\exp (lx) + \exp (ly))$$

logspace.sub(lx, ly):=

$$\log (\exp (lx) - \exp (ly))$$

Usage

logspace.add(lx, ly)
logspace.sub(lx, ly)

Value

a numeric vector of the same length as x+y.

Arguments

lx, ly

numeric vectors, typically of the same length, but will be recycled to common length as with other R arithmetic.

Author

Morten Welinder (for R's pgamma()); Martin Maechler

See Also

lsum, lssum; then pgamma()

Examples

Run this code
set.seed(12)
ly <- rnorm(100, sd= 50)
lx <- ly + abs(rnorm(100, sd=100))  # lx - ly must be positive for *.sub()
stopifnot(exprs = {
   all.equal(logspace.add(lx,ly),
             log(exp(lx) + exp(ly)), tol=1e-14)
   all.equal(logspace.sub(lx,ly),
             log(exp(lx) - exp(ly)), tol=1e-14)
})

Run the code above in your browser using DataLab