Skip to content

Instantly share code, notes, and snippets.

@MattSurabian
Created July 14, 2013 13:17
Show Gist options
  • Save MattSurabian/5994243 to your computer and use it in GitHub Desktop.
Save MattSurabian/5994243 to your computer and use it in GitHub Desktop.
My implementation of the Errors Exercise in Go, printing errors if a negative number is run through the Sqrt function. Part of the Go tour: http://tour.golang.org/#55
package main
import (
"fmt"
"math"
)
const(
ACCURACY_DELTA = 0.00000000000001 // Experiment with this value to see accuracy impact!
)
type ErrNegativeSqrt float64
func (e ErrNegativeSqrt) Error() string{
return fmt.Sprintf("Cannot Sqrt negative number: %g", float64(e))
}
func Sqrt(x float64) (float64, error){
if x < 0 {
return 0, ErrNegativeSqrt(x)
}
ourGuess := float64(1) // any initial guess will do!
for newtonGuess := newtonIteration(x, ourGuess); math.Abs(newtonGuess-ourGuess) > ACCURACY_DELTA
{
ourGuess = newtonGuess;
newtonGuess = newtonIteration(x, ourGuess)
}
return ourGuess, nil
}
func newtonIteration(x, z float64) float64{
return z-(math.Pow(z,2)-x)/(2*z)
}
func main() {
// Is there really not a better syntax for this error handling?
res, err := Sqrt(2)
if err != nil {
fmt.Println(err)
}else{
fmt.Println(res)
}
res, err = Sqrt(-2)
if err != nil {
fmt.Println(err)
}else{
fmt.Println(res)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment