I have an issue when trying to implement the code for Newton's Method for finding the value of the square root (using iterations). I'm trying to get the function to stop printing the values once a certain accuracy is reached, but I can't seem to get this working. Below is my code.
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
Why won't the if-statement work?
This should work:
MySqrt <- function (x, eps = 1e-6, itmax = 100, verbose = TRUE){
i <- 1
myvector <- vector(mode='numeric',itmax) ## better to allocate memory
GUESS <- readline(prompt="Enter your guess: ")
GUESS <- as.numeric(GUESS)
myvector[i] <- GUESS
while(i <= itmax){
GUESS <- (GUESS + (x/GUESS)) * 0.5
if (abs(GUESS-myvector[i]) < eps) break
i <- i + 1
myvector[i] <- GUESS
}
myvector[seq(i)]
}
MySqrt(2)
Enter your guess: 1.4
[1] 1.400000 1.414286 1.414214
Please see @RichieCotton's comment to @agstudy's answer. I agree with Richie, and in fact it makes more sense to use @agstudy's approach.
Your function is fine, your math is off.GUESS
and x
should not (necessarilly) be close, but GUESS * GUESS
and x
should be.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With