Reputation: 63
Among many intuitive solutions online, I've trying hard to understand this one implementation which was posted on r/golang.
Just to enrich the context, here's the problem statement in the golang tutorial:
As a way to play with functions and loops, let's implement a square root function: given a number x, we want to find the number z for which z² is most nearly x.
Here's the link to the post and here's the code from that post which I've slightly changed to understand it better:
package main
import (
"fmt"
)
func Sqrt(x, z float64) float64 {
z -= ((z*z - x) / (2*z))
for z*z > x {
z -= ((z*z - x) / (2*z))
}
return z
}
func main() {
fmt.Println(Sqrt(100, 1))
}
How is it that for any given value of z and x, z^2 always ends up a greater value than x in the first iteration (that is before the beginning of the for loop)?
I have this doubt since I wonder if there's a way whereby both z^2 is less than x and the returned z is an incorrect root to x.
I'm mostly convinced that z^2 cannot be less than x in the first iteration since I couldn't find any combination of z and x proving otherwise, in so far as I could try. I would greatly appreciate an explanation as to why z^2 is always greater than x on the first iteration, if indeed that is true.
Upvotes: 1
Views: 123
Reputation: 1549
this is because z -= ((z * z - x) / (2*z)) is equal to
z = z - ((z * z - x) / (2*z))
because in first place value of z is always way less than x so z * z - x will be negative
and we have z - (negative value ) so this will be positive for example a-(-b) = a+b
but as z starts to grow the value z*z - x will become less and less
Upvotes: 0