Created
December 25, 2013 01:36
-
-
Save kaipakartik/8119441 to your computer and use it in GitHub Desktop.
Exercise: Errors
Copy your Sqrt function from the earlier exercises and modify it to return an error value. Sqrt should return a non-nil error value when given a negative number, as it doesn't support complex numbers
http://tour.golang.org/#56
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 ErrNegativeSqrt float64 | |
func (e ErrNegativeSqrt) Error() string { | |
return fmt.Sprintf("cannot Sqrt negative number : %v", float64(e)) | |
} | |
func Sqrt(x float64) (float64, error) { | |
if x < 0 { | |
return 0, ErrNegativeSqrt(x) | |
} | |
next := float64(1) | |
prev := float64(0) | |
for math.Abs(next - prev) > .01 { | |
prev, next = next, next - (next*next - x)/(2*next) | |
} | |
return next, nil | |
} | |
func main() { | |
fmt.Println(Sqrt(2)) | |
fmt.Println(Sqrt(-2)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
nice implementation!