Random Numbers
This Go code demonstrates the use of the rand
package to generate random numbers. Let's go through the code with inline comments and explanations:
Output
Explanation:
Generating Random Integers:
rand.Intn(100)
generates a random integer between 0 and 99.
Generating Random Floating-Point Numbers:
rand.Float64()
generates a random floating-point number between 0.0 and 1.0.(rand.Float64()*5)+5
generates a random floating-point number in the range [5.0, 10.0).
Seeding Random Number Generator:
rand.NewSource(time.Now().UnixNano())
creates a new source using the current Unix timestamp as the seed.rand.New(s1)
creates a new random number generator using the source.
Consistent Random Numbers with the Same Seed:
Using a specific seed (42) results in the same sequence of random numbers each time.
This code demonstrates the basic usage of the rand
package in Go to generate random numbers, both integers and floating-point, with and without seeding. Seeding is useful to ensure reproducibility if needed.
Last updated
Was this helpful?