go-Newton method square root

func main() {
	fmt.Println(sqrt(3))

}

func sqrt(x float64)float64{
	 z := x
	for i := 0; i < 10 ; i++  {
		z = z - (z*z -x)/(2*z)
	}
	return z
}

 

Function as a simple way to exercise and cycling, to achieve prescribing function by Newton's method.

In this example, Newton's method is by selecting an initial point  z  and repeat this procedure seeking  Sqrt(x) approximation:

To do this, we need to be repeated only 10 times was calculated and the effects of different values ​​(1,2,3, ......) how the results of successive approximation. Then, modified cycling conditions, such that when the change is stopped when the value (or a very small change) to exit the loop. Whether observed changes in the number of iterations. Results and [[http://golang.org/pkg/math/#Sqrt][math.Sqrt] approaching it?

Tip: define and initialize a floating-point value, or to provide it using a floating point conversion syntax:

Guess you like

Origin www.cnblogs.com/prader6/p/11992590.html