μx
pratio <- function(z, mu_x=1.0, mu_y=1.0,var_x=0.2, var_y=0.2) {
sd_x <- sqrt(var_x)
sd_y <- sqrt(var_y)
a <- function(z) {
sqrt(z*z/var_x+1/var_y)
}
b <- function(z) {
mu_x*z/var_x + mu_y/var_y
}
c <- mu_x^2/var_x + mu_y^2/var_y
d <- function(z) {
exp((b(z)^2 - c*a(z)^2)/(2*a(z)^2))
}
t1 <- (b(z)*d(z)/a(z)^3)
t2 <- 1.0/(sqrt(2*pi)*sd_x*sd_y)
t3 <- pnorm(b(z)/a(z)) - pnorm(-b(z)/a(z))
t4 <- 1.0/(a(z)^2*pi*sd_x*sd_y)
t5 <- exp(-c/2.0)
return(t1*t2*t3 + t4*t5)
}
# Integrates to 1, so probably no typos.
print(integrate(pratio, lower=-Inf, upper=Inf))
cdf_ratio <- function(x, mu_x=1.0, mu_y=1.0,var_x=0.2, var_y=0.2) {
integrate(function(x) {pratio(x, mu_x, mu_y, var_x, var_y)},
lower=-Inf, upper=x, abs.tol=.Machine$double.eps)$value
}
# Numerical differentiation here is very easy:
derv_mu_x <- function(x, mu_x=1.0, mu_y=1.0,var_x=0.2, var_y=0.2) {
eps <- sqrt(.Machine$double.eps)
left <- cdf_ratio(x, mu_x+eps, mu_y, var_x, var_y)
right <- cdf_ratio(x, mu_x-eps, mu_y, var_x, var_y)
return((left - right)/(2*eps))
}