Skip to content

Instantly share code, notes, and snippets.

@akisute
Created June 2, 2013 12:38
Show Gist options
  • Save akisute/5693523 to your computer and use it in GitHub Desktop.
Save akisute/5693523 to your computer and use it in GitHub Desktop.
// http://go-tour-jp.appspot.com/#23
package main
import (
"fmt"
"math"
)
func Sqrt(x float64) float64 {
z := 1.0
for i := 0; i < 10; i++ {
z = z - ((z*z - x) / (2*z))
}
return z
}
func Sqrt2(x float64) (float64, int) {
i := 0
z := 1.0
for {
i++
if zz := z - ((z*z - x) / (2*z)); math.Abs(zz-z) < 0.0001 {
break
} else {
z = zz
}
}
return z, i
}
func main() {
for i := 1; i < 10; i++ {
// Pattern A
// fmt.Println(i, Sqrt(float64(i)))
// Pattern B
z, n := Sqrt2(float64(i))
fmt.Println(i, z, n)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment