RANDOM - Get a pseudo random integer number

Language reference ›› Built-in functions ›› Miscellaneous ››
Parent Previous Next

random-function = RANDOM [ "(" scale-expression | random-size ")" ] .
scale-expression = unsigned-integer-constant-expression .
random-size = BYTE | WORD | LONGWORD .

NEW! (V2.1): Returns a pseudo random number with the requested range (unsigned).

The random number generator is based on a fast LFSR method, which is a good compromise between code size and a quite flat distribution.

If not initialized with a specific seed, the random sequence is always the same. To have a different sequence, use RANDOMIZE with a known random signal, e.g.: an analog input value or a running counter value at a random event like push-button press or communication interrupt.

With no argument, RANDOM is equivalent to RANDOM(BYTE) and returns a BYTE range 0..255.

With a <scale-expression> argument the returned value range is 0 .. <unsigned-integer-constant-expression> - 1.  

Scaled numbers greater than a LONGWORD range cannot be achieved because it would generate a 64-bit overflow during the scaling math.

Scaling math for a BYTE expression range is: (WORD(RANDOM(BYTE)) * WORD(<scale-expression>)) SHR 8.

Scaling math for a WORD expression range is: (LONGWORD(RANDOM(WORD)) * LONGWORD(<scale-expression>)) SHR 16.

Scaling math for a LONGWORD expression range is: (BIGWORD(RANDOM(LONGWORD)) * BIGWORD(<scale-expression>)) SHR 32.

Note: As seen above, using a variable for scaling uses the immediately greater math format, so the code size may be an issue.


 RND_W := RANDOM(1000); // Get a random value in a 0..999 range.
 RND_W := RANDOM;       // Get a random value in a 0..255 range.
 RND_W := RANDOM(WORD); // Get a random value in a 0..65535 range.
 RND_W := RANDOM(MaxWord); // Get a random value in a 0..65535 range.
 RND_W := RANDOM(RND_M); // Get a 16-bit random value in a 0..(RND_M - 1) range; scaling uses using 32-bit math.

See also: RANDOMIZE.