[R] Root finding problem
Sergey Goriatchev
sergeyg at gmail.com
Mon Sep 24 11:20:06 CEST 2007
Hello,
I have a problem finding a root of a function, which I define like this:
tuki <- function(u, x, a, lambda){
if((lambda%%1>0) & u<0) {u<-(u+0i)}
f <- Re(x-(a*(u)^lambda-(1-(u))^lambda)/lambda)
f
}
What I want to do is to find the root, but without specifying the
interval within which to search for it. I can do it easily in MATLAB
with fsolve() or fzero() functions.
I compared results of running root-finding in MATLAB and R:
1) I found (by hand) a suitable interval of u-values for a=5,
lambda=0.5 and ran uniroot for x from 1 to 5:
ex.: uniroot(tuki, c(-1,1), x=1, a=5, lambda=0.5)
The results are the same as I get in MATLAB.
2) nlm() does not find the correct value!!!
ex.: nlm(tuki, p=0.1, x=1, a=5, lambda=0.5)
3) if I change lambda to 1.5, while keeping a=5, root finding in
MATLAB returns the following results for x from 1 to 5:
0.5134
0.7330
0.9345
1.1289 - 0.0058i
1.3085 - 0.0199i
With correctly chosen interval, uniroot() finds correct values only
for x = 1:3, not for x=4 or x=5. (Obviously, I return real value from
tuki, but without that uniroot() does not work, returning "Error in
f(lower, ...) * f(upper, ...) > 0 : invalid comparison with complex
values")
There is noone here to ask about this problem, and I just don't know
what to do. :-( Again, what I want is to find the root of the
above-mentioned function, for arbitrary values of x, a, and lambda,
and just specifying one value for u as a starting guess. Could anyone
please give me a suggestion of how to do that? Thanks in advance.
In MATLAB I do the following:
function u=tukeysolve(a,lambda,xgrid)
u=zeros(length(xgrid),1);
old=0.001; % just a guess
for i=1:length(xgrid)
x=xgrid(i);
u(i) = fsolve(@tuki,old,optimset('Display','Off','tolf',5e-8),x,a,lambda);
old=u(i); % use previous value as new start value
end
function f=tuki(u,x,a,lambda)
f = x - (a * u^lambda - (1-u)^lambda)/lambda;
More information about the R-help
mailing list