Skip to content

Instantly share code, notes, and snippets.

@satyrius
Last active December 26, 2015 07:09
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save satyrius/7113364 to your computer and use it in GitHub Desktop.
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…
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