TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

<< Back to GO

Golang rand, crypto: Random Number Generators

Use the rand package and generate random numbers. Call rand.Int and Seed.
Rand. Everything, even the color of the grass, may be deterministic in this world. But many events seem random. We use "math/rand" in Go to simulate this effect.
With rand.Int we get random integers. And with rand.Seed we initialize the pseudo-random number generator that the Go language uses.
An intro program. This program generates 5 pseudo-random numbers. It uses a default seed value (which initializes the generator) of 1.

So: The program generates the same numbers each time. Try running it multiple times—it always has the same result.

Int: This method returns a positive (non-negative) int. No fractional or negative values are possible.

Tip: To change the initial series of values returned by rand.Int, use the Seed method.

Golang program that uses rand.Int package main import ( "fmt" "math/rand" ) func main() { // Loop five times. for i := 0; i < 5; i++ { // Get random positive integer. value := rand.Int() fmt.Println(value) } } Output 5577006791947779410 8674665223082153551 6129484611666145821 4037200794235010051 3916589616287113937
Seed. This method initializes the random source. When we use a seed based on the current time, each program execution will start with a different random sequence.

Here: We use the current Nanoseconds from the time. We cast this to an int64 to seed the number generator.

Time

Note: If you run this program many times, each execution will print a different random number.

Golang program that uses Seed package main import ( "fmt" "math/rand" "time" ) func main() { // Call Seed, using current nanoseconds. rand.Seed(int64(time.Now().Nanosecond())) // Random int will be different each program execution. value := rand.Int() fmt.Println(value) } Output 6912970929678809162
Rand.Perm. This function is useful. It generates slices of Ints with values from 0 to the max index of the slice. Each value appears only once. So it creates permutations of Ints.

Here: We call rand.Perm with an argument of 5. So the numbers 0, 1, 2, 3, and 4 are randomly arranged in slices of 5 elements.

Important: Perm uses the default random source. So we would need to use Seed to avoid the same output on each program run.

Golang program that uses rand.Perm package main import ( "fmt" "math/rand" ) func main() { for i := 0; i < 5; i++ { // Use rand.Perm to generate a random array of numbers. numbers := rand.Perm(5) fmt.Println(numbers) } } Output [0 4 2 3 1] [4 1 2 0 3] [2 3 0 4 1] [0 4 2 1 3] [1 0 4 2 3]
Crypto rand. Random numbers come in varying levels of randomness. For the best random numbers built into Go, we should use crypto rand. We must use the "math/big" package.

Program: We call the rand.Int method in "crypto/rand" 20 times. We get values that are from 0 to 99 inclusive (we never get 100).

Golang program that uses crypto rand package main import ( "crypto/rand" "math/big" "fmt" ) func main() { // Generate 20 random numbers with exclusive max of 100. // ... So max value returned is 99. // All values returned are 0 or greater as well. for i := 0; i < 20; i++ { result, _ := rand.Int(rand.Reader, big.NewInt(100)) fmt.Println(result) } } Output 54 77 56 21 56 81 55 16 57 88 95 58 12 74 23 35 72 29 25 68
Some research. Here is some research on Seed. If we do not use Seed each program execution will yield the same numbers. So we should seed with time or another source of randomness.

Note: The programs in this example set should all use rand.Seed for optimally random behavior.

Quote: Use the Seed function to initialize the default Source if different behavior is required for each run.

Rand: golang.org
Global versus local. With top-level rand methods, we use a global source. But we can create Rand instances that are local. This helps with many randomness requirements.
© TheDeveloperBlog.com
The Dev Codes

Related Links:


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf