[R] Solving two nonlinear equations with two knowns
Berend Hasselman
bhh at xs4all.nl
Fri Jul 17 18:51:34 CEST 2009
yhsu6 wrote:
>
>
> ##########
> #R code:
> mu2=0.4
> sigma2=4
> tau=0.75
> mean.diff=2
> var.ratio=3
>
> #Use optim:
> parameter<-function(c)
> {
> a<-c[1]
> b<-c[2]
> u<-runif(10000)
> Y<-qnorm(u,mean=mu2,sd=sigma2)
> u<-runif(10000)
> X<-qnorm(u,mean=mu2,sd=sigma2)+a*abs(u-tau)^b*(u>tau)
> return((abs(mean(X)-mean(Y))-mean.diff)^2+(var(X)/var(Y)-var.ratio)^2)
> }
>
>
> c0<-c(3,1)
> cstar<-optim(c0,parameter)$par
> astar<-cstar[1] #4.1709
> bstar<-cstar[2] #-0.2578
>
>
Your problem is ill posed.
In your function you have two u <- runif(10000) statements
This means that every time your function is called, u changes.
You can see this happening by repeating parameter(c0) several times
parameter(c0)
[1] 7.346233
parameter(c0)
[1] 7.204457
So you are trying to optimise a function that gives different results for
the same parameter vector every time it is called. You can't determine a
and b that way.
This will never work.
The two u<-runif(10000) should be removed from the function body and should
be done only once before calling the function.
Your function then becomes
zparameter<-function(c)
{
a<-c[1]
b<-c[2]
Y<-qnorm(u,mean=mu2,sd=sigma2)
X<-qnorm(u,mean=mu2,sd=sigma2)+a*abs(u-tau)^b*(u>tau)
z<-numeric(2)
z[1] <- abs(mean(X)-mean(Y))-mean.diff
z[2] <- var(X)/var(Y)-var.ratio
z
}
BTW: you can make this function more efficient by moving the expression for
Y outside the function body and writing X<=Y+.....
If you do this, you should get sensible results. For solving a system of
equation I would not use optim.
Use an equation solver (nleqslv or BB).
Berend
--
View this message in context: http://www.nabble.com/Solving-two-nonlinear-equations-with-two-knowns-tp24528892p24538026.html
Sent from the R help mailing list archive at Nabble.com.
More information about the R-help
mailing list