[英]Newton root finding function does not work with sqrt(x) in R
Currently doing a homework exercise based on root finding algorithms:目前正在做一个基于寻根算法的家庭作业:
A root finding algorithm can also be used to approximate certain functions.求根算法也可用于逼近某些函数。 Show mathematically how the evaluation of the square root function f(x) = √x can be expressed as a root finding problem.4 Use both Newton's method and the bisection method to approximate √x for different values of x.
以数学方式说明平方根函数 f(x) = √x 的评估如何表示为求根问题。4 使用牛顿法和二分法来近似 x 的不同值的 √x。 Compare your approximations with the R function sqrt.
将您的近似值与 R 函数 sqrt 进行比较。 For which values of x does the approximation work well?
对于 x 的哪些值,近似值工作得很好? Does Newton's method or the bisection method perform better?
牛顿法还是二分法性能更好? How do the answers to these questions depend on your starting value?
这些问题的答案如何取决于您的起始值?
I have the following code that worked for every function so far:到目前为止,我有以下代码适用于每个功能:
newton.function <- function(f, fPrime, nmax, eps, x0){
n <- 1
x1 <- x0
result <- c()
while((n <= nmax) && (abs(f(x1)) >= eps)){
x1 <- (x0 - (f(x0)/fPrime(x0)))
result <- c(result, x1)
n <- n + 1
x0 <- x1
}
iterations <- n - 1
return(c(iterations, result[length(result)]))
}
Sqrt functions:平方函数:
g <- function(x){
x^(1/2)
}
gPrime <- function(x){
1/(2*x^(1/2))
}
When I execute the function I either get Error in if (abs(f(x1)) <= eps) break : missing value where TRUE/FALSE needed or if the x0 = 0 I get 1 and 0 as a result.当我执行该函数时,我要么在 if (abs(f(x1)) <= eps) break 中得到错误:缺少需要 TRUE/FALSE 的值,或者如果 x0 = 0 我得到 1 和 0 结果。
newton.function(f = g, fPrime = gPrime, nmax = 1000, eps = 1E-8, x0 = 0)
My bisection function works equally as bad, I am stuck answering the question.我的二分功能同样糟糕,我无法回答这个问题。
From a programming point of view, your code works as expected.从编程的角度来看,您的代码按预期工作。
If you start with 0, which is the exact solution, you get 0, fine.如果你从 0 开始,这是精确的解,你会得到 0,很好。
Now look what happens when starting with any other number:现在看看从任何其他数字开始时会发生什么:
x1 <- (x0 - (f(x0)/fPrime(x0))) = (x0 - (x0^(1/2)/(1/(2*x^(1/2)))))
= x0-2x0 = -x0
So if you start with a positive number, x1
will be negative after the first iteration, and the next call to f(x1)
returns NaN
since you ask the square root of a negative number.因此,如果您从一个正数开始,则在第一次迭代后
x1
将为负数,并且由于您询问负数的平方根,因此对f(x1)
的下一次调用将返回NaN
。
The error message tells you that R can not evaluate abs(f(x1)) >= eps
to TRUE or FALSE, indeed, abs(f(x1))
returns NaN and the >=
operator returns also NaN
in this case.错误消息告诉您 R 无法将
abs(f(x1)) >= eps
评估为 TRUE 或 FALSE,实际上, abs(f(x1))
返回 NaN 并且在这种情况下>=
运算符也返回NaN
。 This is exactly what the error message tells you.这正是错误消息告诉您的内容。
So I advice you to look at some mathematics source to check you algorithm, but the R part is ok.所以我建议你看一些数学资料来检查你的算法,但 R 部分没问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.