Add errors

This commit is contained in:
Alex D. 2021-04-30 17:08:51 +00:00
parent 393cb66cae
commit df812f2af2
Signed by: caskd
GPG Key ID: F92BA85F61F4C173
1 changed files with 26 additions and 0 deletions

26
sqrterr.go Normal file
View File

@ -0,0 +1,26 @@
package main
import (
"fmt"
)
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)
}
z := 1.0
for count := 0; count < 10; count++ {
z -= (z*z - x) / (2*z)
}
return z, nil
}
func main() {
fmt.Println(Sqrt(2))
fmt.Println(Sqrt(-2))
}