go-learning/tour_of_go/l5/exercise-errors.go
2025-08-31 17:38:50 +01:00

42 lines
841 B
Go

package main
import (
"fmt"
)
type ErrNegativeSqrt float64
func (e ErrNegativeSqrt) Error() string {
return fmt.Sprintf("cannot Sqrt negative number: %v", float64(e))
}
func Sqrt(x float64) (float64, error) {
if x < 0 {
return 0, ErrNegativeSqrt(x)
}
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, nil
}
} else if (old_z - z) < precision {
fmt.Println("Required precision has been reached after", iter, "iterations! Square root of", x , "is", z)
return z, nil
}
}
return z, nil
}
func main() {
fmt.Println(Sqrt(2))
fmt.Println(Sqrt(-2))
}