在尝试实现牛顿方法的代码以找到平方根的值时(使用迭代),我遇到了一个问题.我试图让功能在达到一定精度后停止打印值,但我似乎无法使其正常工作.以下是我的代码.
MySqrt <- function (x, eps = 1e-6, itmax = 100, verbose = TRUE){
i <- 1
myvector <- integer(0)
GUESS <- readline(prompt="Enter your guess: ")
GUESS <- as.integer(GUESS)
while(i <= itmax){
GUESS <- (GUESS + (x/GUESS)) * 0.5
myvector <- c(myvector, GUESS)
if (abs(GUESS-x) < eps) break
i <- i + 1
}
myvector
Run Code Online (Sandbox Code Playgroud)
为什么if语句不起作用?
请参阅@RichieCotton 对@agstudy 答案的评论。我同意 Richie 的观点,事实上使用 @agstudy 的方法更有意义。
你的功能很好,但你的数学不行。
GUESS和x不应该(必然)接近,但是GUESS * GUESS和x应该接近。
MySqrt <- function (x, eps = 1e-6, itmax = 100, verbose = TRUE){
i <- 1
myvector <- integer(0)
GUESS <- readline(prompt="Enter your guess: ")
GUESS <- as.integer(GUESS)
while(i <= itmax){
GUESS <- (GUESS + (x/GUESS)) * 0.5
myvector <- c(myvector, GUESS)
browser(expr={i == 10 || abs(GUESS-x) < eps})
if (abs((GUESS*GUESS)-x) < eps) break ### <~~~~ SEE HERE
i <- i + 1
}
myvector
}
Run Code Online (Sandbox Code Playgroud)