LoginSignup
1
2

More than 5 years have passed since last update.

Go言語でfloatの乱数を範囲指定で生成する

Last updated at Posted at 2017-04-05

randパッケージはIntn()で範囲指定の乱数を生成できるが,floatでは出来ないので下記のコードで生成する.

main.go
package main

import (
    "fmt"
    "math/rand"
    "time"
)

func random(min, max float64) float64 {
    rand.Seed(time.Now().UnixNano())
    return rand.Float64()*(max-min) + min
}

func main() {
    max, min := 0.0, 5.0
    for i := 0; i < 5; i++ {
        fmt.Println(random(max, min))
    }
}

実行結果

$ go run main.go
4.5879148973737935
3.7805664986881684
0.4223481031130064
2.6733873103691015
4.961673820044476
1
2
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
1
2