Search code examples
rloopsrepeatnewtons-method

R loop to approximate square root of a positive real number with Newton's method


I am new to R and I'm working on a homework question which asks me to use a repeat loop using Newton's method for square root approximation. Here is what I have so far:

x = 2
a = 10
tol = 1e-04
repeat {
  (abs(x^2 - a) > tol)
  (x = 0.5 * (a/x + x))
  if (all.equal(x^2, a)) {
    break
  }
}

But I am getting some error message plus a wrong answer. In the end, a should nearly equal x ^ 2 but it doesn't yet. I know there is something wrong with the all.equal portion, but I'm trying to figure out how to break the loop once they are close enough.

Thank you for any suggestions.


Solution

  • Don't use all.equal at all.

    ## trying to find `sqrt(10)`
    x <- 2
    a <- 10
    tol <- 1e-10
    repeat{
      x <- 0.5 * (a / x + x)
      if (abs(x * x - a) < tol) break
      }
    x
    #[1] 3.162278