math.rand
Defined in module
"math"from "math" import randReturns a random integer in range 0..RAND_MAX
Return value
An integer in the closed range 0 to math.RAND_MAX.
Notes
The generator is a linear congruential one over a 32-bit seed held in the shared state. Its arithmetic wraps at 32 bits, so the same seed gives the same sequence of results on every platform and every build.
The seed starts randomized when the process starts, so a rand() call with no prior srand call is not reproducible. Call srand with a fixed seed first when a script needs the same numbers on every run.
The seed lives in the shared state, one per VM rather than one per module, so a seed set from any module changes what every module's rand() returns next.
Example
from "math" import rand, srand, RAND_MAX
// seed first: an unseeded rand() is not reproducible, so examples always seed
srand(1)
println("rand() =", rand())
println("rand() =", rand())
println("rand() =", rand())
// every draw stays within the documented range
let r = rand()
println("r >= 0 && r <= RAND_MAX =", r >= 0 && r <= RAND_MAX)Output:
rand() = 1015571940
rand() = 1586027347
rand() = 18251880
r >= 0 && r <= RAND_MAX = trueSee also
srand | Sets the seed for rand() |
RAND_MAX | The largest value rand() can return; rand() results span 0..RAND_MAX. |
| math | module index |