Skip to content

Instantly share code, notes, and snippets.

@poppen
Created November 23, 2013 03:11
Show Gist options
  • Select an option

  • Save poppen/7610291 to your computer and use it in GitHub Desktop.

Select an option

Save poppen/7610291 to your computer and use it in GitHub Desktop.
An answer of the exercise: Errors on a tour of go
package main
import (
"fmt"
"math"
)
type ErrNegativeSqrt float64
func (e ErrNegativeSqrt) Error() string {
return fmt.Sprintf("cannot Sqrt negative number: %f", e)
}
func Sqrt(f float64) (float64, error) {
if f < 0 {
e := ErrNegativeSqrt(f)
return 0, e
}
z := 1.0
var prev_z float64
for math.Abs(prev_z - z) > 1e-10 {
prev_z = z
z = z - ((z*z - f) / (z * 2))
}
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