Golang exercises (i) loops and functions

Source: Internet
Author: User
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))}





Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.