go-learning/tour_of_go/l3/ex1.go

33 lines
628 B
Go
Raw Permalink Normal View History

2025-08-30 12:55:18 +00:00
package main
import (
"fmt"
)
func Sqrt(x float64) float64 {
precision := 0.00001
old_z := 0.0
z := x
iter := 0
for (z - old_z) > precision {
iter += 1
old_z := z
z -= (z*z - x) / (2*z)
if old_z - z < 0 {
if ((old_z - z) * -1) < precision {
fmt.Println("Required precision has been reached after", iter, "iterations! Square root of", x , "is", z)
return z
}
} else if (old_z - z) < precision {
fmt.Println("Required precision has been reached after", iter, "iterations! Square root of", x , "is", z)
return z
}
}
return z
}
func main() {
fmt.Println(Sqrt(2))
fmt.Println(Sqrt(29))
}