Skip to content

Instantly share code, notes, and snippets.

@cloneko
Created May 10, 2014 18:35
Show Gist options
  • Save cloneko/dbbc8371449d8e343b97 to your computer and use it in GitHub Desktop.
Save cloneko/dbbc8371449d8e343b97 to your computer and use it in GitHub Desktop.
A tour of Go #24 Exercise: Loops and Functions http://go-tour-jp.appspot.com/#24 の ニュートン法 を使った平方根の計算を実装した奴。
package main
import (
"fmt"
"math"
)
func Sqrt(x float64) (float64,int) {
z := 1.0
buf := 0.0
i := 0
for {
z = z - ((math.Pow(z,2) - x) / (2 * x))
if z == buf {
return z,i
}
buf = z
i++
}
}
func main() {
target := float64(128)
fmt.Println(Sqrt(target))
fmt.Println(math.Sqrt(target))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment