github.com/maenmax/kairep@v0.0.0-20210218001208-55bf3df36788/src/golang.org/x/tour/solutions/errors.go (about) 1 // Copyright 2012 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 // +build ignore 6 7 package main 8 9 import ( 10 "fmt" 11 "math" 12 ) 13 14 type ErrNegativeSqrt float64 15 16 func (e ErrNegativeSqrt) Error() string { 17 return fmt.Sprintf("Sqrt: negative number %g", e) 18 } 19 20 const delta = 1e-10 21 22 func Sqrt(f float64) (float64, error) { 23 if f < 0 { 24 return 0, ErrNegativeSqrt(f) 25 } 26 z := f 27 for { 28 n := z - (z*z-f)/(2*z) 29 if math.Abs(n-z) < delta { 30 break 31 } 32 z = n 33 } 34 return z, nil 35 } 36 37 func main() { 38 fmt.Println(Sqrt(2)) 39 fmt.Println(Sqrt(-2)) 40 }