[R] Uniroot error
Berend Hasselman
bhh at xs4all.nl
Sat Apr 7 20:23:59 CEST 2012
On 07-04-2012, at 19:48, jeka12386 wrote:
> Dear All
>
> I am trying to find a uniroot of a function within another function (see
> example) but I am getting an error message (f()values at end points not of
> opposite sign). I was wondering if you would be able to advise how redefine
> my function so that I can find the solution. In short my first function
> calculates the intergrale which is function of "t" , I need to find the
> uniroot of n defined in the second function.
>
> y <- function(t){
> (dnorm(t,mean=(diff*sqrt(n/2)),sd=sqrt(rho)))*(pnorm((qnorm((1-alpha),mean=0,sd=1)-t)/(sqrt(1-rho))))^2
> }
>
> inter <- function(n){
> integrate(y,lower=-Inf,upper=Inf)$value-0.8
> }
>
> rho <- 0.5
> alpha <- 0.0125
> diff <- 0.5
>
> n1 <- uniroot(inter,lower=1,upper=100000)$root
>
When I run your example as presented by you, R issues an error message:
Error in dnorm(t, mean = (diff * sqrt(n/2)), sd = sqrt(rho))
object 'n' not found
Calls: uniroot -> f -> integrate -> <Anonymous> -> f -> dnorm
Execution halted
Indeed, the argument n of function inter is not passed to function y, which is using n (and is not global).
Your example I changed to this:
y <- function(t, n) {
(dnorm(t, mean=(diff*sqrt(n/2)),
sd=sqrt(rho)))*(pnorm((qnorm((1-alpha),mean=0,sd=1)-t)/(sqrt(1-rho))))^2
}
inter <- function(n) {
integrate(y,lower=-Inf,upper=Inf, n=n)$value-0.8
}
rho <- 0.5
alpha <- 0.0125
diff <- 0.5
n1 <- uniroot(inter,lower=1,upper=100000)
n1
Changes: n added to arguments of y and argument n of function inter passed to y.
Output:
$root
[1] 9.210123
$f.root
[1] -6.86966e-11
$iter
[1] 9
$estim.prec
[1] 6.103516e-05
Finally: do realize that argument t of function y will be a vector (that's what integrate does).
Berend
More information about the R-help
mailing list