Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@janlay
Created March 15, 2012 09:40
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save janlay/2043291 to your computer and use it in GitHub Desktop.
Save janlay/2043291 to your computer and use it in GitHub Desktop.
Tour of Go #43: implement the square root function using Newton's method.
package main
import (
"fmt"
"math"
)
func Sqrt(x float64) float64 {
z := 1.0
for i := 1; i <= 100; i++ {
if value := z - (z * z - x) / (2 * z); math.Abs(value - z) < 0.0000001 {
return value
} else {
z = value
}
}
return z
}
func main() {
fmt.Println(Sqrt(10))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment