Generating Random Numbers in Golang



Random numbers play an important role in many applications, from computer games to cryptography. Go has a built-in package called "math/rand" that provides a suite of functions to generate random numbers. In this article, we will explore how to use the "math/rand" package to generate random numbers in Go.

Generating a Random Integer

To generate a random integer, we can use the "Intn()" function from the "math/rand" package. The "Intn()" function takes an integer n as its argument and returns a random integer between 0 and n-1.

Example

package main import ( "fmt" "math/rand" ) func main() { // Generating a random integer between 0 and 99 randomInt := rand.Intn(100) fmt.Println(randomInt) } 

Output

81 

Generating a Random Float

To generate a random floating-point number, we can use the "Float64()" function from the "math/rand" package. The "Float64()" function returns a random float between 0.0 and 1.0.

Example

package main import ( "fmt" "math/rand" ) func main() { // Generating a random float between 0.0 and 1.0 randomFloat := rand.Float64() fmt.Println(randomFloat) } 

Output

0.6046602879796196 

Setting a Seed Value

To generate the same sequence of random numbers each time the program is run, we can set a seed value using the "Seed()" function from the "math/rand" package. The "Seed()" function takes an integer as its argument and initializes the random number generator.

Example

package main import ( "fmt" "math/rand" "time" ) func main() { // Setting a seed value to generate a different sequence of random numbers each time rand.Seed(time.Now().UnixNano()) // Generating a random integer between 0 and 99 randomInt := rand.Intn(100) fmt.Println(randomInt) // Generating a random float between 0.0 and 1.0 randomFloat := rand.Float64() fmt.Println(randomFloat) } 

Output

56 0.295370367780173 

Generating a Random Permutation

To generate a random permutation of a slice, we can use the "Perm()" function from the "math/rand" package. The "Perm()" function takes an integer n as its argument and returns a random permutation of the integers [0, n).

Example

package main import ( "fmt" "math/rand" ) func main() { // Generating a random permutation of integers [0, 5) perm := rand.Perm(5) fmt.Println(perm) } 

Output

[0 4 2 3 1] 

Conclusion

In this article, we have explored how to generate random numbers in Go using the "math/rand" package. We learned how to generate random integers and floating-point numbers, set a seed value to generate the same sequence of random numbers, and generate random permutations of slices.

Updated on: 2023-04-18T09:31:37+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements