Skip to content

Instantly share code, notes, and snippets.

@krry
Created March 4, 2019 00:42
Show Gist options
  • Select an option

  • Save krry/8ed2635a2c96a1652896f1dfdfc9cdb0 to your computer and use it in GitHub Desktop.

Select an option

Save krry/8ed2635a2c96a1652896f1dfdfc9cdb0 to your computer and use it in GitHub Desktop.
An Answer to A Tour of Go Exercise: Errors
package main
import (
"fmt"
"math"
)
type ErrNegSqrt float64
func (e ErrNegSqrt) Error() string {
return fmt.Sprintf("cannot Sqrt negative number: %v", float64(e))
}
func Sqrt(x float64) (float64, error) {
if x < 0 {
return 0, ErrNegSqrt(x)
}
z := 1.0
for {
if math.Abs(z - (z - (z*z - x) / (2*x))) < 1e-16 {
return z, nil
} else {
z -= (z*z - x) / (2*x)
}
}
}
func main() {
fmt.Println(Sqrt(2))
fmt.Println(Sqrt(-2))
}
// returns:
// 1.414213562373095 <nil>
// 0 cannot Sqrt negative number: -2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment