• Go语言学习笔记-A Tour of Go 练习笔记-Loops and Functions


    Exercise: Loops and Functions

    题目:

    As a way to play with functions and loops, let's implement a square root function: given a number x, we want to find the number z for which z² is most nearly x.

    Computers typically compute the square root of x using a loop. Starting with some guess z, we can adjust z based on how close z² is to x, producing a better guess:

    z -= (z*z - x) / (2*z)

    Repeating this adjustment makes the guess better and better until we reach an answer that is as close to the actual square root as can be.

    Implement this in the func Sqrt provided. A decent starting guess for z is 1, no matter what the input. To begin with, repeat the calculation 10 times and print each z along the way. See how close you get to the answer for various values of x (1, 2, 3, ...) and how quickly the guess improves.

    Hint: To declare and initialize a floating point value, give it floating point syntax or use a conversion:

    z := 1.0
    z := float64(1)

    Next, change the loop condition to stop once the value has stopped changing (or only changes by a very small amount). See if that's more or fewer than 10 iterations. Try other initial guesses for z, like x, or x/2. How close are your function's results to the math.Sqrt in the standard library?

    (Note: If you are interested in the details of the algorithm, the z² − x above is how far away z² is from where it needs to be (x), and the division by 2z is the derivative of z², to scale how much we adjust z by how quickly z² is changing. This general approach is called Newton's method. It works well for many functions but especially well for square root.)

    练习程序:

    1. package main
    2. import (
    3. "fmt"
    4. "math"
    5. )
    6. func Sqrt(x float64) float64 {
    7. z := 1.0
    8. for math.Abs(z*z - x) > 0.00000001 {
    9. z -= (z*z - x) / (2 * z)
    10. }
    11. fmt.Println(z)
    12. return z*z
    13. }
    14. func main() {
    15. fmt.Println(Sqrt(2))
    16. fmt.Println("The sqrt is", math.Sqrt(2))
    17. }

    运行结果:

    1. 1.4142135623746899
    2. 2.0000000000045106
    3. The sqrt is 1.4142135623730951

    学习笔记:

    该程序使用著名的牛顿迭代发求解一个函数值的平方根,通过程序实现了当平方根的解在一定精度范围内,即可输出。

  • 相关阅读:
    MediaPlayer_Analyze-5-NuPlayer
    Apache DolphinScheduler 3.0.0 升级到 3.1.8 教程
    javaEE学生期末综合测评系统
    docker自定义镜像与上传
    安装依赖报错
    Puppeteer结合测试工具jest使用(四)
    科学高效备考AMC8和AMC10竞赛,吃透2000-2024年1850道真题和解析
    ORCID以及ResearcherID注册
    ARM 汇编指令作业(求公约数、for循环实现1-100之间和、从SVC模式切换到user模式简单写法)
    Vue2:官方路由 Vue-Router 3.x
  • 原文地址:https://blog.csdn.net/sxmatch/article/details/127808790