Notice: On April 23, 2014, Statalist moved from an email list to a forum, based at statalist.org.
From | "Luigi Pinoni" <gipino9@gmail.com> |
To | <statalist@hsphsun2.harvard.edu> |
Subject | st: nonlinear equation: finding zeros |
Date | Fri, 24 Jun 2011 00:19:26 +0200 |
Dear all, I have an apparently simple problem of finding zeros to nonlinear equations. I was told that mata can easily do the trick but I must say that I am completely new to it and struggling to enter its programming language. I have also searched the statalist but either I am left with most of my doubts or I keep finding reference to the FAQ: http://www.stata.com/support/faqs/lang/nl.html, which I am struggling to implement (so, please, do not redirect me to it again?). Let me now explain my problem. I need a command to numerically computes the zeroes of one equation. For instance, consider the single equation: 0=exp(-R*w)-exp(-R*(w+5000))/2-exp(-R*(w-z))/2 Assume that (for instance) w=1000 and z=10. Can Stata tell me what is the value of the scalar R that make the RHS of the equation above equal to zero (in my example it is R=0.06931471806)? Actually, all variables mentioned above (w,z) are Nx1 vectors, i.e. w and z are three variables in a Stata data set and I need to generate the Nx1 vector of solutions, row by row. In other words, the actual problem I have is to find the N zeros of equations: 0=exp(-R[i]*w[i])-exp(-R[i]*(w[i]+5000))/2-exp(-R[i]*(w[i]-z[i]))/2 Knowing the value of w[i] and z[i], for all i=1,?,N. I have tried to find this R following the FAQ mentioned above (using mata) but Stata issues some mistakes that I am unable to interpret. Could you please tell me where I am going wrong? I do appreciate your help and please accept my apologies for the naivety of my mata coding. All the best! ********** BEGINNING OF MY EXAMPLE clear all set obs 10 gen w=. replace w=915000 in 1 replace w=1000 in 2 replace w=4000 in 3 replace w=250000 in 4 replace w=280000 in 5 replace w=330000 in 6 replace w=500 in 7 replace w=498000 in 8 replace w=410000 in 9 replace w=520000 in 10 gen z=. replace z=500 in 1 replace z=10 in 2 replace z=1000 in 3 replace z=1000 in 4 replace z=100 in 5 replace z=5000 in 6 replace z=1000 in 7 replace z=5000 in 8 replace z=100 in 9 replace z=2000 in 10 mata void mysolver(todo, p, lnf, S, H) { p=(1..10) lnf=( exp(-R*w[1])-exp(-R*(w[1]+5000))/2-exp(-R*(w[1]-z[1]))/2)^2 } S = optimize_init() optimize_init_evaluator(S, &mysolver()) optimize_init_evaluatortype(S, "v0") optimize_init_params(S, (1)) optimize_init_which(S, "min" ) optimize_init_tracelevel(S,"none") optimize_init_conv_ptol(S, 1e-16) optimize_init_conv_vtol(S, 1e-16) p = optimize(S) p end ********** END OF MY EXAMPLE * * For searches and help try: * http://www.stata.com/help.cgi?search * http://www.stata.com/support/statalist/faq * http://www.ats.ucla.edu/stat/stata/