Last active
August 29, 2015 14:18
-
-
Save evandertino/38f05bbf5c8abd30e54c to your computer and use it in GitHub Desktop.
Go Exercise: Loops and Functions - http://tour.golang.org/flowcontrol/8
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
| package main | |
| import ( | |
| "fmt" | |
| "math" | |
| ) | |
| func Sqrt(x float64) float64 { | |
| z, delta := 1.0, 0.0000001 | |
| for i :=0; i <= 100; i++ { // limit iterations to 100 | |
| if value := z - (z * z - x) / (2 * z); math.Abs(value - z) < delta { | |
| // Delta reached, return value | |
| return value | |
| } else { | |
| // Continue assigning | |
| z = value | |
| // Show iterations done | |
| fmt.Println(z) | |
| } | |
| } | |
| // Loop ended, return value | |
| return z | |
| } | |
| func main() { | |
| fmt.Println(Sqrt(10), math.Sqrt(10)) | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Now handles errors
https://gist.github.com/evandertino/4129baab2b02200137c0#file-sqrt_err-go