Last active
December 26, 2015 07:09
-
-
Save satyrius/7113364 to your computer and use it in GitHub Desktop.
A Tour of Go.
Exercise: Loops and Functions. 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 an…
This file contains 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" | |
) | |
func Sqrt(x float64) float64 { | |
z := 1.0 | |
for i := 1; i <= 10; i++ { | |
z = z - (z * z - x) / (2 * z) | |
} | |
return z | |
} | |
func main() { | |
nums := []float64{1, 2, 3, 4} | |
for _, v := range nums { | |
fmt.Println(Sqrt(v), math.Sqrt(v)) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment