Newton's method in R

I had a problem trying to implement code for the Newton method to determine the square root value (using iterations). I am trying to get a function to stop printing values ​​as soon as a certain accuracy is reached, but I cannot get this to work. 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 does the if statement not work?

+6
source share
2 answers

UPDATE:

Check out @RichieCotton's comment for @agstudy's answer. I agree with Richie, and it actually makes sense to use the @agstudy approach.


Original answer:

Your function is fine, your math is off.
GUESS and x should not (necessarily) 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 } 
+3
source

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 
+3
source

Source: https://habr.com/ru/post/956035/


All Articles