我试图用R编写牛顿·拉普森程序:
mle_estimate <- function(x,start, eps, t_i_begin, error_begin){
t0 <- start
t_i_next <- t_i_begin
error <- error_begin
while (error >= eps) {
t_i_next <- t0 - first_partial(x, t0)/second_partial(x, t0)
error <- abs(t_i_next - t0)
t0 <- t_i_next
}
return (t_i_next)
}
但是,当我使用以下程序测试程序时:
x <- c(1.77, -0.23, 2.76, 3.8, 3.47, 56.75, -1.34,
4.24, -2.44, 3.29, 3.71, -2.4, 4.53, -0.07, -1.05,
-13.87, -2.53, -1.75, 0.27, 43.21)
mle_estimate(x, 10, 5, 3, 12)
我收到了以下警告 警告消息:
1: In while (error >= eps) { ... :
the condition has length > 1 and only the first element will be used
2: In while (error >= eps) { ... :
the condition has length > 1 and only the first element will be used
3: In while (error >= eps) { ... :
the condition has length > 1 and only the first element will be used
4: In while (error >= eps) { ... :
the condition has length > 1 and only the first element will be used
有人知道为什么“条件长度> 1 ...”的消息吗?因为我在while循环中的情况似乎只是变量“ error”和“ eps”的当前值的比较?
编辑:这是我的偏导数:
first_partial <- function(x, theta_current){
fp <- 0
fp <- sum((2*(x-theta_current))/((x-theta_current)^2 + 1))
return (fp)
}
second_partial <- function(x, theta_current){
sp <- 0
sp <- (-2*(x-theta_current)*((x-theta_current)^2+1) + 4*(x-theta_current)*(x-theta_current))/(((x-theta_current)^2 + 1)^2)
}