Last active
May 26, 2019 02:33
-
-
Save yixiaoyx/002010d714226d179adcdbcc5907cd49 to your computer and use it in GitHub Desktop.
A Tour of Go exercise
This file contains 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
// Implement square root calculation | |
package main | |
import ( | |
"fmt" | |
"math" | |
) | |
// my solution | |
func Sqrt(x float64) (float64, float64) { | |
z := x/2 | |
zp := x | |
i := 1 | |
for math.Abs(z-zp) > 0.000000000000001 { | |
zp = z | |
z -= (z*z - x) / (2*z) | |
i++ | |
//fmt.Println("z is", z) | |
} | |
fmt.Println("loop count:", i) | |
return zp | |
} | |
func main() { | |
n := 99 // change to any real number | |
fmt.Println("My calculation:", Sqrt(n)) | |
fmt.Println("Library result:", math.Sqrt(n)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment