Skip to content

Instantly share code, notes, and snippets.

@zainfathoni
Created April 10, 2017 10:57
Show Gist options
  • Save zainfathoni/1a76009c08b6340fc9d1f96fce47c7ab to your computer and use it in GitHub Desktop.
Save zainfathoni/1a76009c08b6340fc9d1f96fce47c7ab to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"math"
)
const DELTA = 0.00000000001
const INITIAL_Z = 100.0
func Sqrt(x float64) (z float64, err error) {
if x < 0 {
return z, ErrNegativeSqrt(x)
}
z = INITIAL_Z
step := func() float64 {
return z - (z*z - x) / (2 * z)
}
for zz := step(); math.Abs(zz - z) > DELTA
{
z = zz
zz = step()
}
return
}
type ErrNegativeSqrt float64
func (e ErrNegativeSqrt) Error() string {
return fmt.Sprint("cannot Sqrt negative number: ",
float64(e))
}
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