Skip to content

Instantly share code, notes, and snippets.

@takatoshiono
Created September 2, 2016 13:22
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 takatoshiono/64d97549355631a5654c70fb0bc15d97 to your computer and use it in GitHub Desktop.
Save takatoshiono/64d97549355631a5654c70fb0bc15d97 to your computer and use it in GitHub Desktop.
A Tour of Go: Exercise: Errors, https://go-tour-jp.appspot.com/methods/20
package main
import (
"fmt"
"math"
)
type ErrNegativeSqrt float64
func (e ErrNegativeSqrt) Error() string {
return fmt.Sprint("cannot Sqrt negative number: ", float64(e))
}
func Sqrt(x float64) (float64, error) {
if x < 0 {
return 0, ErrNegativeSqrt(x)
}
z := 1.0
z_before := 0.0
count := 0
for i := 0; math.Abs(z-z_before) > 0.0000001; i++ {
z_before = z
z = z - (math.Pow(z, 2)-x)/(2*z)
count += 1
}
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