Skip to content

Instantly share code, notes, and snippets.

@bilsalak
Created December 2, 2018 00:40
Show Gist options
  • Save bilsalak/a0bd45c2994ef30791adb839068f0183 to your computer and use it in GitHub Desktop.
Save bilsalak/a0bd45c2994ef30791adb839068f0183 to your computer and use it in GitHub Desktop.
A Tour of Go - Exercise: Loops and Functions - Part 3
// See https://gist.github.com/bilsalak/a53cddbee61647eea9de552193cfcedf for part 2
//
// Try other initial guesses for z, like x, or x/2. How close are your function's
// results to the math.Sqrt in the standard library?
package main
import (
"fmt"
"math"
)
func Sqrt(x float64) float64 {
z := (x / 2)
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, " using custom Sqrt function")
fmt.Println(Sqrt(i))
fmt.Println("calculating Sqrt of ", i, " using math.Sqrt function")
fmt.Println(math.Sqrt(i))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment