Skip to content

Instantly share code, notes, and snippets.

@thebyrd
Last active January 4, 2016 02:08
Show Gist options
  • Save thebyrd/8552541 to your computer and use it in GitHub Desktop.
Save thebyrd/8552541 to your computer and use it in GitHub Desktop.
As a simple way to play with functions and loops, implement the square root function using Newton's method. In this case, Newton's method is to approximate Sqrt(x) by picking a starting point z and then repeating: To begin with, just repeat that calculation 10 times and see how close you get to the answer for various values (1, 2, 3, ...). Next,…
package main
import (
"fmt"
"math"
)
const Delta = 0.0001
func Sqrt(x float64) float64 {
z := 1.0
tmp := 0.0
for {
tmp = z - (z * z - x) / 2.0 * z
if d := tmp - z; math.Abs(d) < Delta {
return tmp
}
z = tmp
}
return z
}
func main() {
attempt := Sqrt(2)
expected := math.Sqrt(2)
fmt.Printf("attempt = %g\n", attempt)
fmt.Printf("expected = %g\n", expected)
fmt.Printf("error = %g\n", attempt - expected)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment