dtgj8529 2018-04-10 06:38
浏览 1216
已采纳

使用Golang生成特定范围内的随机float64数字

package main

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

func genRandNums(min, max float64) []float64 {
    var randNums []float64
    s := rand.NewSource(time.Now().Unix())
    r := rand.New(s)
    for x := 0; x < 10; x++ {
        // generate random float in range of min and max inclusive, append
        // to randNums and return randNums
    }
    return randNums
}

func main() {
    nums := genRandNums(1.10, 101.98)
    fmt.Println(nums)
}

I have tried searching online on how to accomplish this, but I only found out how to generate random integers in a range. Is there any way I can generate random floats in a range using Go stdlib?

  • 写回答

1条回答 默认 最新

  • douna2917 2018-04-10 06:47
    关注

    Simply use rand.Float64() to get a random number in the range of [0..1), and you can map (project) that to the range of [min..max) like this:

    r := min + rand.Float64() * (max - min)
    

    And don't create a new rand.Rand and / or rand.Source in your function, just create a global one or use the global one of the math/rand package. But don't forget to initialize it once.

    Here's an example function doing that:

    func randFloats(min, max float64, n int) []float64 {
        res := make([]float64, n)
        for i := range res {
            res[i] = min + rand.Float64() * (max - min)
        }
        return res
    }
    

    Using it:

    func main() {
        rand.Seed(time.Now().UnixNano())
        fmt.Println(randFloats(1.10, 101.98, 5))
    }
    

    Output (try it on the Go Playground):

    [51.43243344285539 51.92791316776663 45.04754409242326 28.77642913403846
        58.21730813384373]
    

    Some notes:

    • The code on the Go playground will always give the same random numbers (time is fixed, so most likely the Seed will always be the same, also output is cached)
    • The above solution is safe for concurrent use, because it uses rand.Float64() which uses the global rand which is safe. Should you create your own rand.Rand using a source obtained by rand.NewSource(), that would not be safe and neither the randFloats() using it.
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 对于这个复杂问题的解释说明
  • ¥50 三种调度算法报错 采用的你的方案
  • ¥15 关于#python#的问题,请各位专家解答!
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败