generate a random number between 0 and 1 in go

To generate a random number between 0 and 1 in Go, you can use the math/rand package and the Float64() function. Here's an example:

main.go
package main

import (
	"fmt"
	"math/rand"
)

func main() {
	// Seed the random number generator
	rand.Seed(42)

	// Generate a random float64 between 0 and 1
	randomNumber := rand.Float64()

	// Print the random number
	fmt.Println(randomNumber)
}
249 chars
18 lines

In this example, we first seed the random number generator using the Seed() function. This ensures that we get a different sequence of random numbers each time we run the program. We then generate a random float64 between 0 and 1 using the Float64() function. Finally, we print the random number using the fmt.Println() function.

related categories

gistlibby LogSnag