Archive

Posts Tagged ‘approximation’

The square root function using Newton’s method

February 3, 2014 1 comment

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

Categories: golang, math Tags: , ,

Seconds in one year

October 24, 2011 Leave a comment

In 1 year there are about seconds.

Exact value:

365 * 24 * 60 * 60 = 31536000

Approximation:

>>> math.pi * 10**7
31415926

Difference:

120074 seconds, i.e. 33.35 hours.
Categories: Uncategorized Tags: , , ,
Design a site like this with WordPress.com
Get started