Go by Example: Random Numbers

The math/rand package in Go provides functions for generating random numbers, making it easy to write programs that use random values.

Here’s an example that demonstrates how to use the rand package to generate random numbers:

package main

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

func main() {
	// Seed the random number generator using the current time
	rand.Seed(time.Now().UnixNano())

	// Generate a random integer in the range [0, 10)
	randInt := rand.Intn(10)
	fmt.Println("Random int:", randInt)

	// Generate a random float in the range [0.0, 1.0)
	randFloat := rand.Float64()
	fmt.Println("Random float:", randFloat)
}

In this example, the rand.Seed function is called with the current time in nanoseconds to seed the random number generator. This ensures that each time the program is run, a different sequence of random numbers will be generated.

The rand.Intn function is then used to generate a random integer in the range [0, 10), and the rand.Float64 function is used to generate a random float in the range [0.0, 1.0).

The output of this program will be something like:

Random int: 5
Random float: 0.8483608879808643

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *