Skip to content

Instantly share code, notes, and snippets.

@VOID001 VOID001/SIG1.go
Created May 13, 2016

Embed
What would you like to do?
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
You can’t perform that action at this time.