9
votes

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);

    for i := 0; i < 10; i++ {
        z := z - (z*z - x) / (2 * z);
    }

    return z;
}

Can anyone point out what I'm missing about the language? I think it has to do with = vs. := and scoping, but I'm not sure.

2

2 Answers

12
votes

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
 }
4
votes

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
}