Last active
December 21, 2015 21:39
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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