r - Solve and find x for normally distributed functions -
i'm trying solve equation , find value x
it. i'm using following code:
mu1 = 0 mu2 = 1 sigma1 = 0.5 sigma2 = 0.6 prior1 = 0.3 prior2 = 0.7 boundary = function(x) { return(( 1 / sqrt(2 * pi * sigma1)) * exp(-0.5 * ((x - mu1) / sigma1)^2)*prior1) - ((1 / sqrt(2 * pi * sigma2)) * exp(-0.5 * ((x - mu2) / sigma2)^2)*prior2) } uniroot(boundary, c(-1e+05, 1e+07))
this not give me correct answers. i'm pretty new r , not sure how uniroot
works.
- is there better way solve equation?
- are there packages available solve (similar matlab's
solve()
function)?
you can shorten code little bit (and minimize chance of typos) using built-in dnorm()
function:
curve(dnorm(x,mean=0,sd=0.5),from=-4,to=4) curve(dnorm(x,mean=0,sd=0.6),add=true,col=2)
if try uniroot()
on reasonable range, sensible answers:
uniroot(function(x) dnorm(x,0,0.5)-dnorm(x,0,0.6), c(0,5)) ## 0.546 uniroot(function(x) dnorm(x,0,0.5)-dnorm(x,0,0.6), c(-5,0)) ## -0.546
if try start huge values, calculation going underflow (whether hand or use dnorm()
; gaussian goes below r's minimum representable valuable (see ?.machine
) between 19 , 20.
dnorm(19,0,0.5) ## 2e-314 dnorm(20,0,0.5) ## 0
in cases can use log=true
in dnorm()
compute log-probability , use in computations instead, here (as in many bayesian computations) you're bit stuck because have subtract results.
Comments
Post a Comment