Skip to content

Instantly share code, notes, and snippets.

@yixiaoyx
Last active May 26, 2019 02:33
Show Gist options
  • Save yixiaoyx/002010d714226d179adcdbcc5907cd49 to your computer and use it in GitHub Desktop.
Save yixiaoyx/002010d714226d179adcdbcc5907cd49 to your computer and use it in GitHub Desktop.
A Tour of Go exercise
// 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