Created
December 2, 2018 00:40
-
-
Save bilsalak/a0bd45c2994ef30791adb839068f0183 to your computer and use it in GitHub Desktop.
A Tour of Go - Exercise: Loops and Functions - Part 3
This file contains hidden or 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
// 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