Last active
January 24, 2017 00:36
-
-
Save Bambina-zz/a92965ffbc1583e4ebda7d4b642f42ac to your computer and use it in GitHub Desktop.
関数とループを使った簡単な練習として、 ニュートン法 を使った平方根の計算を実装してみましょう。( https://go-tour-jp.appspot.com/flowcontrol/8 )
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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