Skip to content

Instantly share code, notes, and snippets.

@suzuken
Created March 8, 2014 07:21
Show Gist options
  • Select an option

  • Save suzuken/9426705 to your computer and use it in GitHub Desktop.

Select an option

Save suzuken/9426705 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"math"
)
type ErrNegativeSqrt float64
func (e ErrNegativeSqrt) Error() string {
return fmt.Sprintf("cannot Sqrt negative number: %v", float64(e))
}
func main() {
fmt.Println(Sqrt(2))
fmt.Println(Sqrt(-2))
}
func Sqrt(x float64) (float64, error) {
if x < 0 {
return x, ErrNegativeSqrt(x)
}
z := float64(1)
for i := 0; ; i++ {
z1 := z
z = z - (z * z - x) / 2 * z
if math.Abs(z - z1) <= 0.001 {
return z, nil
}
}
return z, nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment