This is a creation in Article, where the information may have evolved or changed.
Address: HTTP://TOUR.GO-ZH.ORG/FLOWCONTROL/8
Exercise: Loops and functions
As a simple way to practice functions and loops, the root function is realized by Newton method.
In this example, the Newton method is the approximate value that is obtained by selecting an initial point Z and then repeating the process Sqrt(x) :
To do this, you only need to repeat the calculation 10 times, and observe different values (three-in-one, ...). ) is how to approach the results gradually. Then, modify the loop condition so that the value stops changing (or changes very small) when the loop exits. Observe whether the number of iterations changes. results with [[http://golang.org/pkg/math/#Sqrt][math. SQRT] close?
Tip: Define and initialize a floating-point value, provide it with a floating-point syntax, or use a transform:
Z: = float64 (1) Z: = 1.0
Package Mainimport ("FMT") func Sqrt (x float64) float64 {Const E = 0.000001z: = float64 (1) //Note float type k: = float64 (0) for ; ; Z = z-(z*z-x)/(2*z) {if z-k <= E && z-k >=-e {return z}k = Z}}func Main () {FMT. Println (SQRT (2))}