I get this error saying that I\'m not using a variable… but to my noob eyes, it looks like I am:
func Sqrt(x float64) float64 {
z := float64(x);
Here is another way to look at the function
func Sqrt(x float64) (z float64) {
z = x
for i := 0; i < 10; i++ {
z = z - (z*z - x)/(2*z);
}
return
}
The :=
in your for-loop declares a new variable z
which shadows the outer z
. Turn it into a plain =
to fix the problem.
func Sqrt(x float64) float64 {
z := x
for i := 0; i < 10; i++ {
z = z - (z*z - x) / (2 * z);
}
return z;
}
By the way, for equal precision and a bit more speed you could try the following implementation which does two of your steps at once:
func Sqrt(x float64) float64 {
z := x
for i := 0; i < 5; i++ {
a := z + x/z
z = a/4 + x/a
}
return z
}