Created
September 3, 2012 16:15
-
-
Save meirish/3610398 to your computer and use it in GitHub Desktop.
solution for http://tour.golang.org/#58
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 struct { | |
Num float64 | |
} | |
func (e *ErrNegativeSqrt) Error() string { | |
return fmt.Sprintf("cannot Sqrt negative number: %v", e.Num) | |
} | |
func Sqrt(f float64) (float64, error) { | |
result := float64(0) | |
z := float64(2) | |
if f < 0 { | |
err := &ErrNegativeSqrt{f} | |
return result, err | |
} | |
for { | |
z = z - (z*z - f) / (2*z) | |
if math.Abs(result - z) < 1e-15 { | |
break | |
} | |
result = z | |
} | |
return result, 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