Bkk
Bkk

Reputation: 177

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.

Upvotes: 2

Views: 348

Answers (1)

Zheyuan Li
Zheyuan Li

Reputation: 73265

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

Upvotes: 4

Related Questions