Skip to content

Instantly share code, notes, and snippets.

@amstee
Last active January 15, 2017 00:10
Show Gist options
  • Select an option

  • Save amstee/f11b3f6bb45a14e36719409c15f21376 to your computer and use it in GitHub Desktop.

Select an option

Save amstee/f11b3f6bb45a14e36719409c15f21376 to your computer and use it in GitHub Desktop.
An answer for the exercise errors
import (
"fmt"
)
type ErrNegativeSqrt float64
func (e ErrNegativeSqrt) Error() string {
return fmt.Sprintf("cannot Sqrt negative number: %d", int(e))
}
func Sqrt(x float64) (z float64, err error) {
if x < 0 {
err := ErrNegativeSqrt(x)
return 0, err
}
z = 1.0
for i := 0; i < 20; i++ {
z = z - (z * z - x) / (2 * z)
}
return z, nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment