Skip to content

Instantly share code, notes, and snippets.

@tatsuru
Created November 7, 2013 11:53
Show Gist options
  • Save tatsuru/7353409 to your computer and use it in GitHub Desktop.
Save tatsuru/7353409 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"math"
)
func sqrt_newton(x float64) float64 {
z, prev := 1.0, 3.0
const threshold = 1e-15
for {
z -= (z*z - x) / (2*z)
if math.Abs(z-prev) < threshold {
return z
}
fmt.Printf("rest: %g\n", math.Abs(z-prev))
prev = z
}
}
func main() {
fmt.Printf("result: %#v\n", sqrt_newton(2))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment