2

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.

李哲源
  • 59,090
  • 15
  • 146
  • 206
Bkk
  • 77
  • 1
  • 5
  • `if` needs a logical input. `all.equal` does not (necessarily) output a logical value. For example `all.equal(1, 2)`. – IceCreamToucan Oct 01 '18 at 18:38
  • I believe your implementation of the algorithm is wrong but if it were right, you should use `if (isTRUE(all.equal(x^2, a)))`. – Rui Barradas Oct 01 '18 at 18:43

1 Answers1

4

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
李哲源
  • 59,090
  • 15
  • 146
  • 206