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
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.
When you will execute this code, you will get different output each time.
- How to Get Int Type Random Number in Golang?
- How to Get Random Permutation of Integers in Golang?
- How to Get Int31n Type Random Number in Golang?
- How to Get Float32 Type Random Number in Golang?
- How to Get Intn Type Random Number in Golang?
- How to Get Int31 Type Random Number in Golang?
- How to Get Uint32 Type Random Number in Golang?
- How to Get Int63n Type Random Number in Golang?
- How to Get Float64 Type Random Number in Golang?
- How to Get Uint64 Type Random Number in Golang?
- Finding Minimum of Two Numbers in Golang
- Finding Maximum of Two Numbers in Golang
- Golang Program that switch on floating-point numbers
- Generating subarrays using recursion
- Dynamically generating a QR code using PHP
- Mathematics | Generating Functions - Set 2
- How to get random value out of an array in PHP?
- Program to generate random string in PHP
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.