Skip to content

Instantly share code, notes, and snippets.

@kamatama41
Created August 27, 2014 07:14
Show Gist options
  • Save kamatama41/bc7ceb7e4f3ca01c8f73 to your computer and use it in GitHub Desktop.
Save kamatama41/bc7ceb7e4f3ca01c8f73 to your computer and use it in GitHub Desktop.
My answer of "a tour of Go #56( http://go-tour-jp.appspot.com/#56 )"
package main
import (
"fmt"
"math"
)
type ErrNegativeSqrt float64
func (e ErrNegativeSqrt) Error() string {
return fmt.Sprintf("cannot Sqrt negative number: %g", e)
}
func Sqrt(x float64) (float64, error) {
if x < 0 {
return 0.0, ErrNegativeSqrt(x)
}
z, count := 0.5, 1
for ; ; count++ {
old := z
z = z - (z*z-x)/2*z
if math.Abs(float64(old-z)) < 0.0001 {
break
}
}
fmt.Printf("count=%d\n", count)
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