我正在创建一个函数,它可以找到函数的根源。这个特定的算法试图顺序地缩小已知根位于的窗口的宽度。我想要它得到x的函数,窗口和epsilon的值。用户选择Epsilon,越接近于零,根越精确。
这是我的密码:
root.finder <- function(f, x_0, x_1, epsilon) {
if (f(x_0)*f(x_1)>=0)
warning("check values x_0 and x_1")
while(abs(x_1 - x_0) >= epsilon)
x_2 <- (x_0 + x_1)/2
if (f(x_2)*f(x_0) < 0) {
x_1 <- x_2
} else {
x_0 <- x_2
}
print(x_2)
}我试图通过以下方法来测试它:
root.finder(x^3-3*x+1, 0, 1, 1) 但它会跑也不会停下来。这个功能有什么问题?
发布于 2016-12-13 23:29:20
根据注释,我认为您需要将if语句包括在while循环主体中,如下所示:
root.finder <- function(f, x_0, x_1, epsilon) {
if (f(x_0)*f(x_1)>=0)
warning("check values x_0 and x_1")
while(abs(x_1 - x_0) >= epsilon) {
x_2 <- (x_0 + x_1)/2
if (f(x_2)*f(x_0) < 0) {
x_1 <- x_2
} else {
x_0 <- x_2
}
}
print(x_2)
}https://stackoverflow.com/questions/41131951
复制相似问题