Skip to content

Instantly share code, notes, and snippets.

@danimal141
Created October 10, 2016 09:16
Show Gist options
  • Save danimal141/49a8de5177a2a783ce855e4f5494f17e to your computer and use it in GitHub Desktop.
Save danimal141/49a8de5177a2a783ce855e4f5494f17e to your computer and use it in GitHub Desktop.
A Tour of Go Exercise: Errors
package main
import (
"fmt"
"math"
)
type ErrNegativeSqrt float64
func (e ErrNegativeSqrt) Error() string {
return fmt.Sprintf("cannot Sqrt nagative number: %g", e)
}
func Sqrt(x float64) (float64, error) {
z := 1.0
if x < 0 {
return 0, ErrNegativeSqrt(x)
}
for {
z2 := z - (z * z - x) / (z * 2)
if math.Abs(z2 - z) < 1e-10 {
break
}
z = z2
}
return z, nil
}
func main() {
fmt.Println(Sqrt(2))
fmt.Println(math.Sqrt(2))
fmt.Println(Sqrt(-2))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment