R: Logspace Arithmetix - Addition and Subtraction

logspace.add {DPQ} | R Documentation

## 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)

### Arguments

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

### Value

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

### Note

This is really from R's C source code for `pgamma()`, i.e., ‘<R>/src/nmath/pgamma.c’

The function definitions are very simple, `logspace.sub()` using `log1mexp()`.

### Author(s)

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

### See Also

`lsum`, `lssum`; then `pgamma()`

### Examples

    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)
    })

[Package DPQ version 0.4-4 Index]