Implementation of the exercise: Loops and Functions in “A Tour of Go”

Rounak Agarwal
2 min readAug 20, 2019
Golang mascot by Kirael-Art on DeviantArt

A Tour of Go is an interactive introduction to Go covering basic syntax and data structures, methods and interfaces, and Go’s concurrency primitives. It contains a few exercises to help you practice what you’ve learned.

When you begin to take the tour, you will encounter the Loops and Functions exercise which asks you to implement a square root function using Newton’s method. First, you need to repeat the calculation 10 times and print each value along the way. Here is my implementation of the same.

package mainimport (
"fmt"
)
func Sqrt(x float64) float64 {
z := float64(1)
fmt.Printf("Sqrt approximation of %v:\n", x)
for i := 1; i <= 10; i++ {
z -= (z*z - x) / (2*z)
fmt.Printf("Iteration %v, value = %v\n", i, z)
}
return z
}
func main() {
fmt.Println(Sqrt(2))
}

Then, you are asked to change the loop condition to stop once the value has stopped changing (or only changes by a very small amount). Also, you need to find the closeness of your function’s results to the math.Sqrt in the standard library. Here is how I implemented it.

package mainimport (
"fmt"
"math"
)
func Sqrt(x float64) float64 {
z := float64(1)
var t float64
for {
z, t = z - (z*z - x) / (2*z), z
if math.Abs(t-z) < 1e-6 {
break
}
}
return z
}
func main() {
guess := Sqrt(2)
expected := math.Sqrt(2)
fmt.Printf("Guess: %v, Expected: %v, Error: %v", guess, expected, math.Abs(guess - expected))
}

--

--

Rounak Agarwal

Developer | Open Source Contributor | Quizzer | Loves to convert Ideas into Code | Github profile: https://github.com/agarwalrounak