Skip to content

Instantly share code, notes, and snippets.

@rkotov93
Last active March 5, 2016 10:36
Show Gist options
  • Save rkotov93/417acdcde84c9cd12c55 to your computer and use it in GitHub Desktop.
Save rkotov93/417acdcde84c9cd12c55 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"math"
)
// NewtonSqrt calculates sqrt by Newton's method
func NewtonSqrt(x float64) float64 {
const delta = 1e-8
z, zn := 0.0, 1.0
for math.Abs(z-zn) > delta {
z = zn
zn = z - (z*z-x)/(2*z)
}
return zn
}
func main() {
fmt.Println("NewtonSqrt = ", NewtonSqrt(2))
fmt.Println("math.Sqrt = ", math.Sqrt(2))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment