Created
July 14, 2012 17:53
-
-
Save freeformz/3112361 to your computer and use it in GitHub Desktop.
My GoTour Exercise #58 (http://tour.golang.org/#58) solution
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", float64(e)) | |
} | |
func sqrt(target, guess float64) float64 { | |
return guess - (math.Pow(guess, 2)-target)/(2*guess) | |
} | |
func inequiv(a, b float64) bool { | |
return math.Nextafter(a, b) != b | |
} | |
func Sqrt(x float64) (float64, error) { | |
if x < 0 { | |
return 0, ErrNegativeSqrt(x) | |
} | |
curr, guess := 0.0, 10.0 | |
for inequiv(curr, guess) { | |
curr = sqrt(x, guess) | |
guess = (curr + guess) / 2 | |
} | |
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