Created
August 24, 2016 04:12
-
-
Save takatoshiono/b8864c86235c294b7a0e7501128ec5a8 to your computer and use it in GitHub Desktop.
A Tour of Go: Exercise: Loops and Functions (NEXT)
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 | |
import ( | |
"fmt" | |
"math" | |
) | |
func Sqrt(x float64) float64 { | |
z := 1.0 | |
z_before := 0.0 | |
count := 0 | |
for i := 0; math.Abs(z-z_before) > 0.0000001; i++ { | |
z_before = z | |
z = z - (math.Pow(z, 2)-x)/(2*z) | |
count += 1 | |
} | |
fmt.Printf("(loop count:%d) ", count) | |
return z | |
} | |
func main() { | |
for i := 1.0; i < 10; i++ { | |
fmt.Printf("Sqrt(%f) = ", i) | |
fmt.Println( | |
math.Sqrt(i), | |
Sqrt(i), | |
) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
停止条件の差分を
0.0000001
にするとmath.Sqrt
と同じ値になった。一桁減らすと一部の数字で結果が異なった。4, 9は5,6回ループしてるけどこれでいいのかなあ