library (pracma)
newtonRaphson
#this is the code of Newton-Raphson algorithm
#fun is the first derivative of log likelihood function
#dfun is the second
function (fun,x0,dfun=NULL, ... , maxiter=100, tol= .Machine$double.eps^0.5){
if (is.null(dfun)){
dfun<-function(x,...){
h <- tol^(2/3)
(fun(x+h,...) - fun(x-h,...))/(2*h)
}
}
#starting value
x<- x0
fx<- fun(x,...)
dfx<-dfun(x,...)
niter<-0
diff<-tol + 1
#iteration
while (diff >= tol && niter <= maxiter){
niter<-niter+1
if (dfx==0){
warning ("Slope is zero: no further improvement possible")
break
}
diff<- -fx/dfx
x<-x+diff
diff<-abs(diff)
fx<-fun(x,...)
dfx<- dfun(x,...)
}
if (niter> maxiter){
warning ("Maximum number of iterations 'maxiter' was reached")
}
return(list(root=x, f.root=fx, niter=niter, estim.prec=diff))
}
x<-c(3.91,4.85,2.28,4.06,3.70,4.04,5.46,3.53,2.28,1.96,2.53,2.28,1.96,2.53,3.88,2.22,3.47,4.82,2.46,2.99,2.54,0.52,2.50)
df=function(theta2){s=sum(sin(x-theta2)/(1-cos(x-theta2)));s}
d2f=function(theta2){s=sum(((cos(x-theta2))*(1-cos(x-theta2))-(sin(x-theta2))^2)/(1-cos(x-theta2))^2);s}
newtonRaphson(df,-0.418,d2f)
这是我的代码,但是我收到了这个错误:
Error in while (diff >= tol && niter <= maxiter) { :
missing value where TRUE/FALSE needed
我知道它在条件中可能有NA但在while条件下它应该具有TRUE / FALSE值。我不知道为什么。
有人能帮助我吗?
非常感谢!