Skip to content

Instantly share code, notes, and snippets.

@VOID001
Created May 13, 2016 12:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save VOID001/c962ba8670005d63011a8ef8dadeeb52 to your computer and use it in GitHub Desktop.
Save VOID001/c962ba8670005d63011a8ef8dadeeb52 to your computer and use it in GitHub Desktop.
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