That depends. By what amount does the value change in which th loop shall continue? How large would you consider an amount to be, that is not very small?
A common pattern is to check if math.Abs(v2 - v1) <= epsilon where epsilon is the biggest difference which shall be considered as “only small change”, 0.00001 in your case.
Thank you for the hint. I assumed that v2 must be always greater than v1 in terms of used algorithm.
Anyway, I’ve rewritten code according to your comment:
package main
import (
"fmt"
"math"
)
// determination of small change amount
const epsilon = 0.000001
func Sqrt(x float64) float64 {
z := x / 2
z2 := z
var diff float64
for i := 0; i < 10; i++ {
z -= (z*z - x) / (2 * z)
diff = z2 - z
// instead of math.Abs(diff)
if diff < 0 {
diff *= -1
}
fmt.Println(i+1, "; z=", z, "; z2 - z=", z2, "-", z, "=", diff)
if diff <= epsilon {
break
}
z2 = z
}
return z
}
func main() {
x := 3.0
fmt.Println(Sqrt(x), "Sqrt(", x, ")")
fmt.Println(math.Sqrt(x), "math.Sqrt(", x, ")")
}