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.
To avoid this error – Use a blank identifier (_) before the package name os. In the above code, two variables name and age are declared but age was not used, Thus, the following error will return. To avoid this error – Assign the variable to a blank identifier (_).
The identifier is undeclared: In any programming language, all variables have to be declared before they are used. If you try to use the name of a such that hasn't been declared yet, an “undeclared identifier” compile-error will occur.
The subtle difference between = and := is when = used in variable declarations. the above declaration creates a variable of a particular type, attaches a name to it, and sets its initial value. Either the type or the = expression can be omitted, but not both. Besides, := may appear only inside functions.
First, a minor point: declaring a variable that's never used is a waste of memory, and thus is itself a bug.
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
}
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With