Created
August 25, 2018 04:53
-
-
Save johnta0/4ef64e115e76b627ed5c78797c3a258c to your computer and use it in GitHub Desktop.
A Tour of Go 演習問題 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
// ニュートン法で平方根を求める関数を実装する | |
// z -= (z*z - x) / (2*z) | |
package main | |
import ( | |
"fmt" | |
) | |
func Sqrt(x float64) float64 { | |
z := 1.0 | |
for z*z < x { | |
z += 1 | |
} | |
for i := 0; i < 10; i++ { | |
f := z - (z*z - x) / (2*z) | |
if (f*f - x) < (z*z - x) { | |
z = f | |
} | |
if (z*z - x) / (2*z) < z*z - x { | |
} | |
} | |
return z | |
} | |
func main() { | |
fmt.Println(Sqrt(2)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment