Created
May 13, 2016 12:05
-
-
Save VOID001/c962ba8670005d63011a8ef8dadeeb52 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
package main | |
import ( | |
"fmt" | |
"math" | |
) | |
type ErrNegativeSqrt float64 | |
func (e ErrNegativeSqrt) Error() string { | |
return fmt.Sprintf("cannot Sqrt negative number %f", e) | |
} | |
func Sqrt(x float64) (float64, error) { | |
z := float64(100) | |
if x >= 0 { | |
count := 0 | |
realSqrt := math.Sqrt(x) | |
for math.Abs(realSqrt-z) >= 1e-9 { | |
z = z - (z*z-x)/(2*z) | |
count++ | |
fmt.Println("Z[", count, "] =", z) | |
} | |
fmt.Println("Used", count, "time(s) to reach sqrt(x)") | |
return z, nil | |
} | |
return z, ErrNegativeSqrt(x) | |
} | |
func main() { | |
fmt.Println(Sqrt(-5)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment