Last active
December 16, 2015 11:38
-
-
Save vly/5428372 to your computer and use it in GitHub Desktop.
Golang tour #55
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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