dubeegee
dubeegee

Reputation: 781

"declared and not used" Error

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.

Upvotes: 9

Views: 1661

Answers (2)

fuz
fuz

Reputation: 93127

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
 }

Upvotes: 12

Baba
Baba

Reputation: 95161

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
}

Upvotes: 4

Related Questions