Reputation: 177
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
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