Create a gist now

Instantly share code, notes, and snippets.

@Bambina /sqrt.go
Last active Jan 24, 2017

What would you like to do?
関数とループを使った簡単な練習として、 ニュートン法 を使った平方根の計算を実装してみましょう。( https://go-tour-jp.appspot.com/flowcontrol/8 )
package main
// 1.41421 35623 73095 04880
// f(x) = x^2-C (C is given)
// f'(x) = 2x
// 2z0 = z0^2 - C / z0 - z1
// z1 = (zn + C/zn) / 2
import (
"fmt"
)
func Sqrt(x float64) (z1 float64) {
zn := x
for i := 0; i < 10; i++ {
z1 = (zn + x/zn) / 2
if zn == z1 {
fmt.Println(i)
break
} else {
zn = z1
}
}
return
}
func main() {
fmt.Println(Sqrt(2))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment