Computes log(1 + exp(x)) and log(1 - exp(-x)) accurately.

log1mexp(x)
log1pexp(x)

Arguments

x

A vector of reals (numeric). Complex numbers not allowed since expm1 and log1p do not handle these.

Details

Computes log(1 + exp(x)) and log(1 - exp(-x)) accurately. An adjustment is made when \(x\) is away from 0 in value.

Value

log1mexp(x) gives the value of \(\log(1-\exp(-x))\).

log1pexp(x) gives the value of \(\log(1+\exp(x))\).

References

Maechler, Martin (2012). Accurately Computing log(1-exp(-|a|)). Assessed from the Rmpfr package.

Author

This is a direct translation of the function in Martin Maechler's (2012) paper by Xiangjie Xue and T. W. Yee.

Note

If NA or NaN is present in the input, the corresponding output will be NA.

See also

Examples

x <-  c(10, 50, 100, 200, 400, 500, 800, 1000, 1e4, 1e5, 1e20, Inf, NA)
log1pexp(x)
#>  [1] 1.000005e+01 5.000000e+01 1.000000e+02 2.000000e+02 4.000000e+02
#>  [6] 5.000000e+02 8.000000e+02 1.000000e+03 1.000000e+04 1.000000e+05
#> [11] 1.000000e+20          Inf           NA
log(1 + exp(x))  # Naive; suffers from overflow
#>  [1]  10.00005  50.00000 100.00000 200.00000 400.00000 500.00000       Inf
#>  [8]       Inf       Inf       Inf       Inf       Inf        NA
log1mexp(x)
#>  [1]  -4.540096e-05  -1.928750e-22  -3.720076e-44  -1.383897e-87 -1.915170e-174
#>  [6] -7.124576e-218   0.000000e+00   0.000000e+00   0.000000e+00   0.000000e+00
#> [11]   0.000000e+00   0.000000e+00             NA
log(1 - exp(-x))
#>  [1] -4.540096e-05  0.000000e+00  0.000000e+00  0.000000e+00  0.000000e+00
#>  [6]  0.000000e+00  0.000000e+00  0.000000e+00  0.000000e+00  0.000000e+00
#> [11]  0.000000e+00  0.000000e+00            NA
y <- -x
log1pexp(y)
#>  [1]  4.539890e-05  1.928750e-22  3.720076e-44  1.383897e-87 1.915170e-174
#>  [6] 7.124576e-218  0.000000e+00  0.000000e+00  0.000000e+00  0.000000e+00
#> [11]  0.000000e+00  0.000000e+00            NA
log(1 + exp(y))  # Naive; suffers from inaccuracy
#>  [1] 4.53989e-05 0.00000e+00 0.00000e+00 0.00000e+00 0.00000e+00 0.00000e+00
#>  [7] 0.00000e+00 0.00000e+00 0.00000e+00 0.00000e+00 0.00000e+00 0.00000e+00
#> [13]          NA