Skip to content

Instantly share code, notes, and snippets.

@sorah sorah/58.go
Created May 2, 2014

Embed
What would you like to do?
// 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
You can’t perform that action at this time.