LoginSignup
0
0

More than 1 year has passed since last update.

Exercise: Loops and Functions

Last updated at Posted at 2022-01-05

概要

Goのチュートリアル「A Tour of Go」で、関数とループを使って平方根の計算を実装する課題があったので記念に記録します。 時間的には5分程で解きました。「強い」エンジニアの」方々からしたら亀の歩みですね。

初期コード

exercise-loops-and-functions.go
package main

import (
    "fmt"
)

func Sqrt(x float64) float64 {
}

func main() {
    fmt.Println(Sqrt(2))
}

完成コード

exercise-loops-and-functions.go
package main

import (
    "fmt"
    "math"
)

func Sqrt(x float64) float64 {
    z := 1.0

    for i := 1; i <= 10; i++ {

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

        countString := "回目"
        fmt.Println(i, countString, z)

        if math.Sqrt(x) == z {
            break
        }
    }

    return z
}

func main() {
    var num float64 = 2
    fmt.Println(Sqrt(num))
}

特に完成とかはないかと思いますが、チュートリアルで求められている内容はクリアできたかなと思います。

ニュートン法についてはよく解っていません。アルゴリズム弱者なので、2021年は一般人くらいに成長したいですね。

使用したパッケージ

import (
    "fmt"
    "math"
)

fmtはI/Oを整形して使うことができて、mathには数式に関する関数が詰まってます。

まとめ

基本的にはチュートリアルの左側に説明があるので、それさえ読むことができれば問題ないかと思います。今年中にはGopherになりたいですね。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0