Skip to content

Instantly share code, notes, and snippets.

@Bambina-zz
Last active January 24, 2017 00:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Bambina-zz/a92965ffbc1583e4ebda7d4b642f42ac to your computer and use it in GitHub Desktop.
Save Bambina-zz/a92965ffbc1583e4ebda7d4b642f42ac to your computer and use it in GitHub Desktop.
関数とループを使った簡単な練習として、 ニュートン法 を使った平方根の計算を実装してみましょう。( 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