API random

val = math.random([l [, u]]); val = random([l [, u]]);

Description
The functions math.random and math.randomseed are interfaces to the simple random generator functions rand and srand that are provided by ANSI C.

When called without arguments, math.random returns a pseudo-random real number in the range [0,1).

When called with a number n, math.random returns a pseudo-random integer in the range [1,n].

When called with two arguments, l and u, math.random returns a pseudo-random integer in the range [l,u].

The math.randomseed function sets a "seed" for the pseudo-random generator: Equal seeds produce equal sequences of numbers.

On random number generator distribution and security
The ANSI C rand function is a Linear Congruential Pseudo-Random Number Generator (LPCRNG). Statistically speaking, LCPRNGs have a fair distribution. However, from a security standpoint they are very weak.

If you depend on random numbers to keep something secret or someone out of something, they only need to see a handful of numbers to be able to guess the next one accurately. In fact, if you output large enough numbers, they only need to see a single number to determine the next one. This is the standard LCPRNG used by Microsoft (written in C):

rng = rng * 214013 + 2531011 return (rng>>16)&0x7fff;

Example
> local x = math.random; > = x 0.34534 [0 - 1]

> local x = math.random(100); > = x 53 [1 - 100]

> local x = math.random(50, 52); > = x 51 [50 - 52]