Skip to content

Instantly share code, notes, and snippets.

@sorah
Created May 2, 2014 16:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sorah/363bd3825a7a8e1b6989 to your computer and use it in GitHub Desktop.
Save sorah/363bd3825a7a8e1b6989 to your computer and use it in GitHub Desktop.
// http://tour.golang.org/#58
package main
import (
"fmt"
)
type ErrNegativeSqrt float64
func (v ErrNegativeSqrt) Error() string {
return fmt.Sprintf("cannot Sqrt negative number: %f", float64(v))
}
func Sqrt(x float64) (float64, error) {
z := float64(1)
if (x < 0) {
return z, ErrNegativeSqrt(x)
}
for i := 1; i < 100; i++ {
z = z - (z * z - x) / (2 * z)
}
return z, 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