Generating Random Numbers in Golang
Last Updated :
15 Apr, 2020
Golang provides a package math/rand for generating pseudorandom numbers. This package basically uses a single source that causes the production of a deterministic sequence of values each time a program is executed. Here, if you need different output or outcome for each execution, you can use the seed function to initialize the default source which is safe for concurrent use by multiple goroutines. It generates an integer in the interval of 0 and n. It takes only one argument, the n or the upper bound & throws error if argument is less than zero.
RandomInteger := rand.Int() // generates a random integer
RandomIntegerwithinRange: To generate the number within the range where max is the upper bound and min is the lower bound.
RandomIntegerwithinRange := rand.Intn(max-min) + min // range is min to max
rand.Float64(): It generates the floating point number between 0.0 and 1.0, It is as easy as rand.Int to use.
RandomFloatingNumber := rand.Float64() // generates a random floating point number
Example:
package main
import (
"fmt"
"math/rand"
"time"
)
func main() {
fmt.Println( rand .Intn(200))
fmt.Println( rand .Intn(200))
fmt.Println( rand .Intn(200))
fmt.Println()
fmt.Println( rand .Float64())
fmt.Println(( rand .Float64() * 8) + 7)
fmt.Println(( rand .Float64() * 8) + 7)
fmt.Println()
x1 := rand .NewSource( time .Now().UnixNano())
y1 := rand .New(x1)
fmt.Println(y1.Intn(200))
fmt.Println(y1.Intn(200))
fmt.Println()
x2 := rand .NewSource(55)
y2 := rand .New(x2)
fmt.Println(y2.Intn(200))
fmt.Println(y2.Intn(200))
fmt.Println()
x3 := rand .NewSource(5)
y3 := rand .New(x3)
fmt.Println(y3.Intn(200))
fmt.Println(y3.Intn(200))
}
|
Output:
81
87
47
0.4377141871869802
10.397099976570125
12.494584582936875
0
128
112
164
26
36
The above method is not safe if the user wants to keep the random numbers secret. That’s why Golang provides Crypto rand to varies the level of randomness of numbers to come. It is crypto-ready to use and secure but it is slower. It is used for generating passkeys, CSRF tokens or anything related to security.
Example:
package main
import (
"crypto/rand"
"fmt"
)
func main() {
RandomCrypto, _ := rand .Prime( rand .Reader, 128)
fmt.Println(RandomCrypto)
}
|
When you will execute this code, you will get different output each time.
Share your thoughts in the comments
Please Login to comment...