go-tour/exercise-errors.go
2020-02-09 10:44:41 -06:00

29 lines
510 B
Go

package main
import (
"fmt"
"math"
)
type ErrNegativeSqrt float64
func (e ErrNegativeSqrt) Error() string {
return fmt.Sprintf("cannot Sqrt negative number: %f", float64(e))
}
func Sqrt(x float64) (float64, error) {
if x < 0 {
return 0, ErrNegativeSqrt(x)
}
var p float64
for z := 1.0; z != p && math.Abs(z - p) > 0.000000000000001; z -= (z * z - x) / (2 * z) {
p = z
}
return p, nil
}
func main() {
fmt.Println(Sqrt(4))
fmt.Println(Sqrt(-2))
}