33 lines
628 B
Go
33 lines
628 B
Go
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))
|
|
}
|