Created
March 4, 2019 00:42
-
-
Save krry/8ed2635a2c96a1652896f1dfdfc9cdb0 to your computer and use it in GitHub Desktop.
An Answer to A Tour of Go Exercise: Errors
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package main | |
| import ( | |
| "fmt" | |
| "math" | |
| ) | |
| type ErrNegSqrt float64 | |
| func (e ErrNegSqrt) Error() string { | |
| return fmt.Sprintf("cannot Sqrt negative number: %v", float64(e)) | |
| } | |
| func Sqrt(x float64) (float64, error) { | |
| if x < 0 { | |
| return 0, ErrNegSqrt(x) | |
| } | |
| z := 1.0 | |
| for { | |
| if math.Abs(z - (z - (z*z - x) / (2*x))) < 1e-16 { | |
| return z, nil | |
| } else { | |
| z -= (z*z - x) / (2*x) | |
| } | |
| } | |
| } | |
| func main() { | |
| fmt.Println(Sqrt(2)) | |
| fmt.Println(Sqrt(-2)) | |
| } | |
| // returns: | |
| // 1.414213562373095 <nil> | |
| // 0 cannot Sqrt negative number: -2 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment