get a uniformly distributed random number in go

To generate a uniformly distributed random number in Go, we can use the math/rand package. Inside this package there is a function called Float64() that returns a random float64 value between 0.0 and 1.0.

To get a uniformly distributed random number between a specific range, we can use the formula:

main.go
rand.Float64() * (max - min) + min
35 chars
2 lines

where max is the maximum value of the range and min is the minimum value of the range.

Here's some sample code that generates a random number between 1 and 100:

main.go
package main

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

func main() {
    // initialize seed for the random number generator
    rand.Seed(time.Now().UnixNano())

    // generate a random number between 1 and 100
    randomNumber := rand.Float64() * (100 - 1) + 1

    fmt.Println(randomNumber)
}
304 chars
18 lines

Note that we need to initialize the seed for the random number generator to ensure that we get different numbers each time we run the program. In this example, we're using the current time as the seed value.

gistlibby LogSnag