Skip to content

Instantly share code, notes, and snippets.

@vly
Last active December 16, 2015 11:38
Show Gist options
  • Save vly/5428372 to your computer and use it in GitHub Desktop.
Save vly/5428372 to your computer and use it in GitHub Desktop.
Golang tour #55
package main
import (
"fmt"
"math"
)
type ErrNegativeSqrt float64
func (e ErrNegativeSqrt) Error() string {
return fmt.Sprintf("cannot Sqrt negative number: %d", int64(e))
}
func Sqrt(f float64) (float64, error) {
if f < 0 {
return f, ErrNegativeSqrt(f)
}
guess := f/2
t := 0.0
threshold := 0.0000001
for math.Abs(guess - t) > threshold {
t = guess
guess = guess - (guess*guess-f)/(2*guess)
}
return guess, 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