Skip to content

Instantly share code, notes, and snippets.

@kaipakartik
Created December 25, 2013 01:36
Show Gist options
  • Save kaipakartik/8119441 to your computer and use it in GitHub Desktop.
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
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))
}
@nguyenvulong
Copy link

nice implementation!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment