Created
August 27, 2014 07:14
-
-
Save kamatama41/bc7ceb7e4f3ca01c8f73 to your computer and use it in GitHub Desktop.
My answer of "a tour of Go #56( http://go-tour-jp.appspot.com/#56 )"
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: %g", e) | |
} | |
func Sqrt(x float64) (float64, error) { | |
if x < 0 { | |
return 0.0, ErrNegativeSqrt(x) | |
} | |
z, count := 0.5, 1 | |
for ; ; count++ { | |
old := z | |
z = z - (z*z-x)/2*z | |
if math.Abs(float64(old-z)) < 0.0001 { | |
break | |
} | |
} | |
fmt.Printf("count=%d\n", count) | |
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