Skip to content

Instantly share code, notes, and snippets.

@drguildo
Created February 17, 2017 22:19
Show Gist options
  • Save drguildo/52d570a4df1c3a509c96a917d7ecd609 to your computer and use it in GitHub Desktop.
Save drguildo/52d570a4df1c3a509c96a917d7ecd609 to your computer and use it in GitHub Desktop.
A Go implementation of Newton's method for finding the square root of a number.
package main
import (
"fmt"
"math"
)
func Sqrt(x float64) float64 {
return SqrtNewton(x, x)
}
func SqrtNewton(x float64, z float64) float64 {
nextz := z - (z*z-x)/(2*z)
if math.Abs(z-nextz) < 0.001 {
return nextz
}
return SqrtNewton(x, nextz)
}
func main() {
fmt.Println(Sqrt(2))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment