/
probability.R
57 lines (55 loc) · 1.72 KB
/
probability.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
################################################################################
#' Vectorized wrapped normal density function
#'
#' This is a modified version of \code{\link{dwrpnorm}} found in \code{CircStats}
#' to allow for multiple angles at once (i.e., vectorized on theta and mu).
#'
#' @inheritParams CircStats::dwrpnorm
#'
#' @author Eliot McIntire
#' @export
#' @importFrom reproducible compareNA
#' @rdname dwrpnorm2
#'
#' @examples
#' # Values for which to evaluate density
#' theta <- c(1:500) * 2 * pi / 500
#' # Compute wrapped normal density function
#' density <- c(1:500)
#' for(i in 1:500) density[i] <- dwrpnorm2(theta[i], pi, .75)
#' if (interactive()) plot(theta, density)
#' # Approximate area under density curve
#' sum(density * 2 * pi / 500)
#'
dwrpnorm2 <- function(theta, mu, rho, sd = 1, acc = 1e-05, tol = acc) {
if (missing(rho)) {
rho <- exp(-sd ^ 2 / 2)
}
len <- max(length(theta), length(mu), length(rho))
if (length(mu) != len)
mu <- rep(mu, len)
if (length(var) != len)
var <- rep(var, len)
if (length(theta) != len)
theta <- rep(theta, len)
if (rho < 0 | rho > 1)
stop("rho must be between 0 and 1")
var <- -2 * log(rho)
term <- function(theta, mu, var, k) {
1 / sqrt(var * 2 * pi) * exp(-((theta - mu + 2 * pi * k) ^ 2) / (2 * var))
}
k <- 0
Next <- term(theta, mu, var, k)
Last <- Next
delta <- rep(1, length(Last))
while (any(compareNA(delta > tol, TRUE))) {
keep <- delta > tol
keep <- reproducible::compareNA(keep, TRUE)
k <- k + 1
Last[keep] <- Next[keep]
Next[keep] <- Last[keep] + term(theta[keep], mu[keep], var, k) +
term(theta[keep], mu[keep], var, -k)
delta[keep] <- abs(Next[keep] - Last[keep])
}
return(Next)
}