Last active
August 29, 2015 14:14
-
-
Save kumikoda/ba7b1125d67a5a0861e7 to your computer and use it in GitHub Desktop.
Golang tutorial sqrt function with error
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 { | |
// Need to convert e to float64 before passing to Sprint | |
// Or else Sprint will call Error() on e, | |
// and send progrem into infinite loop | |
return fmt.Sprintf("cannot Sqrt negative number: %g", float64(e)) | |
} | |
func Sqrt(x float64) (float64, error) { | |
if (x < 0) { | |
return 0, ErrNegativeSqrt(x) | |
} | |
z := 1.0 | |
for { | |
temp := z - (z*z-x)/(2*z) | |
if math.Abs(temp-z)<0.0000000001 { | |
return temp, nil | |
} | |
z = temp | |
} | |
} | |
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