728x90
package main
import (
"fmt"
"math"
)
func enough(term float64) bool {
if term < 0 { // absolute value
term = -term
}
if term < 0.000000000001 {
return true // enough
} else {
return false // not enough
}
}
func Sqrt(x float64) (float64, int) {
cnt := 0
z := float64(1)
for {
if enough(z*z-x) {
return z, cnt
}
cnt++
z = z-(z*z-x)/(2*z)
}
}
func main() {
var x float64 = 2.0
fmt.Println(Sqrt(x))
fmt.Println("math.sqrt result is ", math.Sqrt(x))
}
결과
--------------------------------------------------------------------------------------------------------------------
참고 http://tech.tigiminsight.com/2015/07/23/algorithm-newton-method.html
728x90