Home > golang, math > The square root function using Newton’s method

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:
newton

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

Advertisements
Categories: golang, math Tags: , ,
  1. February 3, 2014 at 15:37
  1. No trackbacks yet.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: