Create a gist now

Instantly share code, notes, and snippets.

A Tour of Go: Exercise: Loops and Functions (NEXT)
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),
)
}
}
@takatoshiono
Owner

停止条件の差分を0.0000001にするとmath.Sqrtと同じ値になった。一桁減らすと一部の数字で結果が異なった。

Sqrt(1.000000) = (loop count:1) 1 1
Sqrt(2.000000) = (loop count:5) 1.4142135623730951 1.4142135623730951
Sqrt(3.000000) = (loop count:5) 1.7320508075688772 1.7320508075688772
Sqrt(4.000000) = (loop count:5) 2 2.000000000000002
Sqrt(5.000000) = (loop count:6) 2.23606797749979 2.23606797749979
Sqrt(6.000000) = (loop count:6) 2.449489742783178 2.449489742783178
Sqrt(7.000000) = (loop count:6) 2.6457513110645907 2.6457513110645907
Sqrt(8.000000) = (loop count:6) 2.8284271247461903 2.8284271247461903
Sqrt(9.000000) = (loop count:6) 3 3

4, 9は5,6回ループしてるけどこれでいいのかなあ

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment