Skip to content

Instantly share code, notes, and snippets.

@bilsalak
Created December 2, 2018 00:29
Show Gist options
  • Save bilsalak/a53cddbee61647eea9de552193cfcedf to your computer and use it in GitHub Desktop.
Save bilsalak/a53cddbee61647eea9de552193cfcedf to your computer and use it in GitHub Desktop.
A Tour of Go - Exercise: Loops and Functions - Part 2
// See https://gist.github.com/bilsalak/a6016b2e564418402b1431491040f372 for part 1
//
// Next, change the loop condition to stop once the value has stopped changing
// (or only changes by a very small amount). See if that's more or fewer than 10 iterations.
package main
import (
"fmt"
"math"
)
func Sqrt(x float64) float64 {
z := 1.0
last_z := z
change := 1.0
minimum_change := 0.000000000000001
iteration := 0
for change > minimum_change {
z -= (z*z - x) / (2 * z)
change = math.Abs(last_z - z)
last_z = z
iteration++
}
fmt.Println("This answer took ", iteration, " loop iterations")
return z
}
func main() {
for i := 1.0; i < 4; i++ {
fmt.Println("calculating Sqrt of ", i)
fmt.Println(Sqrt(i))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment