为什么我的for循环只向我显示第一个结果?(牛顿法

时间:2019-01-27 23:05:20

标签: r newtons-method

有一个类似的函数:y =(e ^ x-2)^ n x是一个未知数,对于n = 2,3,4,...,8现在,我想使用NR方法为每个n值查找此函数的根(初始x为0)。这是我的代码:

NR <- function(f, tol = 1e-5, ite = 1000){
k <- ite
x0 <- 0
for(n in 2:8){
    for (i in 1:ite){
        #calculate dx
        dx <- genD(func = f, x0)$D[1]
        dx1 <- n * exp(x0) * ((dx - 2) ^ (n - 1))
        #get the x1
        x1 <- x0 - ((f(x0) ^ n) / dx1)
        k[i] <- x1
        if(abs(x1 - x0) < tol){
            root <- x1
            re <- list('root approximation' = root, 'iteration' = length(k))
            return(re)
        }
    x0 <- x1
}
print('Outside the upper iteration')
}
} 

但是此程序仅显示第一个结果(当n = 2时):根近似= 0.6931375,迭代= 15。 好像我的外循环被R忽略了。我不知道为什么,您能帮我解决这个问题吗?

0 个答案:

没有答案
相关问题