1
2
3
4
5
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 }
41
View as plain text