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?
abs(GUESS^2-x)
– Nannettereadline
) from the task of doing the calculation. Functions should do one task, or your code gets confusing. – StrafeGUESS
to int? It just goes back to a double first time thru the loop anyway. – Swashbuckler