Firstly, the algorithm is incorrect. Formula:

You modeled this with:
z - (z*z - x) / 2*z
But it should be:
z - (z*z - x)/2/z
or
z - (z*z - x)/(2*z)
( , 0.001! 4 , 1e-6 x = 2.)
z=1 ( , 2). z = x / 2, .
, , :
z, return "". , , "" , , , . if:
func Sqrt(x float64) (z float64) {
z = x / 2
for i, old := 1, 0.0; ; i++ {
if old, z = z, z-(z*z-x)/2/z; math.Abs(old-z) < 1e-5 {
fmt.Printf("Ran %v iterations\n", i)
return
}
}
}
z = x / 2 for, ( z, ):
func Sqrt(x float64) float64 {
for i, z, old := 1, x/2, 0.0; ; i++ {
if old, z = z, z-(z*z-x)/2/z; math.Abs(old-z) < 1e-5 {
fmt.Printf("Ran %v iterations\n", i)
return z
}
}
}
: 1, "exit" for for.
source
share