Skip to content

Instantly share code, notes, and snippets.

@flc
Last active December 21, 2015 21:39
Show Gist options
  • Save flc/6369384 to your computer and use it in GitHub Desktop.
Save flc/6369384 to your computer and use it in GitHub Desktop.
A Tour of Go - Exercise: Loops and Functions http://tour.golang.org/#24
package main
import (
"fmt"
"math"
)
const e = 1e-8 // small delta
func Sqrt(x float64) float64 {
/*
Newton's method is to approximate Sqrt(x) by picking a
starting point z and then repeating:
z = z - ((z*z - x) / (2*z))
*/
z := x // starting point
for {
new_z := z - ((z*z - x) / (2*z))
if math.Abs(new_z - z) < e {
return new_z
}
z = new_z
}
}
func main() {
fmt.Println(Sqrt(2))
fmt.Println(math.Sqrt(2))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment