Below are two attempts to solve the exercise at https://tour.golang.org/flowcontrol/8. One version makes a function call as part of the for condition, but this doesn't work - it doesn't even execute the loop body. If I move the condition inside the loop itself, it works as I expected. Why?
package main
import (
"fmt"
"math"
)
func Sqrt_working(x float64) float64 {
var z float64 = 1.0
for {
if math.Abs((z*z) - x) < 0.0001 {
break
}
z -= ((z*z - x) / (2*z))
}
return z
}
func Sqrt_not_working(x float64) float64 {
var z float64 = 1.0
for math.Abs((z*z) - x) < 0.0001 {
z -= ((z*z - x) / (2*z))
}
return z
}
func main() {
fmt.Println(Sqrt_working(2))
fmt.Println(Sqrt_not_working(2))
}
Output
1.4142156862745099
1