## The square root function using Newton’s method

Newton’s method approximates `Sqrt(x)`

by picking a starting point `z`

(e.g. `1.0`

) and then repeating:

Let’s see an implementation in Go. We repeat until the value only changes a very small delta. The number of steps is also displayed.

package main import ( "fmt" "math" ) func Sqrt(x float64) float64 { prev, z := 1.0, 1.0 const delta = 0.000000000001 steps := 0 for { z -= (z*z-x) / (2*z) if math.Abs(prev-z) < delta { break } prev = z steps++ } fmt.Println("# steps:", steps) return z } func main() { n := float64(7) fmt.Println(Sqrt(n)) fmt.Println(math.Sqrt(n)) }

Hmm, it seems WordPress.com doesn’t support Go syntax highlighting :(

Output for `Sqrt(7)`

:

# steps: 6 2.6457513110645907 2.6457513110645907

Idea from here: http://tour.golang.org/#25

Categories: golang, math
approximation, Newton, sqrt

Left a ticket on wordpress.com’s forum: http://en.forums.wordpress.com/topic/add-syntax-highlight-support-for-go-aka-golang