Created
May 2, 2014 16:17
-
-
Save sorah/363bd3825a7a8e1b6989 to your computer and use it in GitHub Desktop.
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
// http://tour.golang.org/#58 | |
package main | |
import ( | |
"fmt" | |
) | |
type ErrNegativeSqrt float64 | |
func (v ErrNegativeSqrt) Error() string { | |
return fmt.Sprintf("cannot Sqrt negative number: %f", float64(v)) | |
} | |
func Sqrt(x float64) (float64, error) { | |
z := float64(1) | |
if (x < 0) { | |
return z, ErrNegativeSqrt(x) | |
} | |
for i := 1; i < 100; i++ { | |
z = z - (z * z - x) / (2 * z) | |
} | |
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