简体   繁体   English

Newton-Raphson 求根算法

[英]Newton-Raphson Root Finding Algorithm

Summary of problem问题总结

My objective is to create a function called newton.raphson to implement the Newton-Raphson root-finding algorithm.我的目标是创建一个名为 newton.raphson 的newton.raphson来实现 Newton-Raphson 寻根算法。

Root Finding Algorithm: x1 = X0 - f(xo)/f'(x0)求根算法:x1 = X0 - f(xo)/f'(x0)

I have 2 arguments:我有 2 个 arguments:

  1. iter = number of iteration (value = 10^5) iter = 迭代次数(值 = 10^5)
  2. epsilon = for the tolerance (value = 10^-10) epsilon = 公差(值 = 10^-10)

Can not depend on variables outside of the function不能依赖于 function 之外的变量

newton.raphson <- function(f, x0, iter=1e5, epsilon=1e-10) {
    x <- x0
    h <- 1e-5
    for (t in 1:iter) {
        drvt <- f((x+h)) - f((x-h)) / (2 * h)
        update <- x - f(x)/ drvt
        if (abs(update) < epsilon) {
            break
        }
        x <- update
    }
    root <- x
    return(root)
}
# Define some function to test
f <- function(x) {
    x^2 - 4 * x - 7
}

I get the following results:我得到以下结果:

> newton.raphson(f, 0)
[1] 2.000045
> newton.raphson(f, 3)
[1] 5.000024

But results should be:但结果应该是:

-1.316625
5.316625

Your derivative calculation is a little bit broken - you forgot parenthesis around the difference between f(x+h) and f(xh) :您的导数计算有点错误-您忘记了f(x+h)f(xh)之间差异的括号:

drvt <- ( f(x+h) - f(x-h) ) / (2 * h)

Also, you should compare the difference between the old and new root approximation to the tolerance.此外,您应该将新旧根近似之间的差异与容差进行比较。 In order to make things more clear, rename your misleading update variable to something like new.x .为了使事情更清楚,请将您的误导性update变量重命名为new.x类的东西。 Then, your should check if (abs(new.x - x) < epsilon) .然后,您应该检查if (abs(new.x - x) < epsilon)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM