Skip to content

Instantly share code, notes, and snippets.

@kidinamoto01
Created December 18, 2017 08:57
Show Gist options
  • Save kidinamoto01/dc4bd1de2600130c08440f4750e19cc0 to your computer and use it in GitHub Desktop.
Save kidinamoto01/dc4bd1de2600130c08440f4750e19cc0 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: %.0f", e)
}
func Sqrt(x float64) (float64, error) {
if x < 0 {
return 0, ErrNegativeSqrt(x)
}
t, z := 0., 1.
for {
z, t = z - (z*z-x)/(2*z), z
if math.Abs(t-z) < 1e-8 {
break
}
}
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