Created
May 31, 2018 06:17
-
-
Save nikotung/c4a3ce18070de46d8529ce534f94126c to your computer and use it in GitHub Desktop.
This file contains hidden or 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: %v", float64(e)) | |
} | |
func Sqrt(x float64) (float64, error) { | |
if x < 0 { | |
return 0.0, ErrNegativeSqrt(x) | |
} | |
z := float64(1.0) | |
for i := 0; i < 10; i++ { | |
t := z | |
z = z - (z*z-x)/(2*z) | |
d := math.Abs(z - t) | |
if d < 1e-12 { | |
break | |
} | |
} | |
return z, nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://tour.go-zh.org/methods/20