Thanks a lot Berend and Ravi!!! I am thinking to use integrate command to get theoretical E(X), E(Y), Var(X), and Var(Y). Then the result will not depend on u anymore. After that, I will use dfsane command in BB package.
Kate ---- Original message ---- >Date: Fri, 17 Jul 2009 09:51:34 -0700 (PDT) >From: Berend Hasselman <b...@xs4all.nl> >Subject: Re: [R] Solving two nonlinear equations with two knowns >To: r-help@r-project.org > > > > >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. > >______________________________________________ >R-help@r-project.org mailing list >https://stat.ethz.ch/mailman/listinfo/r-help >PLEASE do read the posting guide http://www.R-project.org/posting-guide.html >and provide commented, minimal, self-contained, reproducible code. ______________________________________________ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.