logSum {tileHMM}R Documentation

Calculate log(x + y) from log(x) and log(y)

Description

Given log(x) and log(y) this function calculates log(x + y) using the identity

# log(x + y) = log(x) + log(1 + exp[log(y) - log(x)])

Usage

logSum(x, y = NULL, base = 0)

Arguments

x Numeric vector or matrix.
y Numeric vector or matrix of same dimensions as x or missing.
base Base of the logarithm to be used. If base is 0 the natural logarithm is used.

Details

If y is missing the function is applied recuresively to all elements of x, i.e., all elements of x are added up. If both x and y are given they are added element wise.

Value

If only x is given a scalar is returned, representing the sum of all elements of x. Otherwise a vector or matrix of the same dimensions as x and y.

Note

This function is useful for cases where x and y cannot be represented accurately by machine numbers but log(x) and log(y) can.

Author(s)

Peter Humburg

Examples

    x <- 1:4
    y <- 4:1
    ## calculate sum of x an y directly
    xy.s <- x + y
    ## and after log transformation
    xy.ls <- logSum(log(x),log(y))
    ## errors are small:
    err <- xy.ls - log(xy.s) 

[Package tileHMM version 1.0-2 Index]