Generate random float64 numbers in specific range using Golang

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.

Leave a Comment