Skip to content

Instantly share code, notes, and snippets.

@NikoTung
Created May 31, 2018 06:17
Show Gist options
  • Save NikoTung/c4a3ce18070de46d8529ce534f94126c to your computer and use it in GitHub Desktop.
Save NikoTung/c4a3ce18070de46d8529ce534f94126c 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: %v", float64(e))
}
func Sqrt(x float64) (float64, error) {
if x < 0 {
return 0.0, ErrNegativeSqrt(x)
}
z := float64(1.0)
for i := 0; i < 10; i++ {
t := z
z = z - (z*z-x)/(2*z)
d := math.Abs(z - t)
if d < 1e-12 {
break
}
}
return z, nil
}
@NikoTung
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment