rnd( max )

Generates a random number between 0 and the given maximum.

The range, non-inclusive.

The rnd() function returns a random number in a range. The result is between 0 and the given maximum, inclusive of 0 but exclusive of the maximum.

The random number includes a fractional part. To get a random integer, use flr(rnd(max)).

The random number generator is initialized with an unpredictable seed value when Pico-8 starts. You can reinitialize the generator with an explicit seed (such as to test random behaviors with a known sequence) using srand().

Working with ranges Edit

To select a random number between a minimum and a maximum, call rnd() with the size of the range, then add the minimum:

x = rnd(32) + 64       -- a random number between 64 and 96
scale = rnd(20) - 10   -- a random number between -10 and 10
die = flr(rnd(6)) + 1  -- a random integer between 1 and 6

To select a random fraction with a fixed number of decimal digits, use flr(rnd(...)) with the range times the precision, then divide by the precision:

earnings = flr(rnd(50 * 100)) / 100  -- between 0.00 and 50.00

Alternate ranges Edit

Undocumented feature
This article describes a feature that is not mentioned in the official Pico-8 documentation. The feature was known to work at the time the article was written, but it may be removed or changed in a future version.

rnd() called with a negative value for max returns a random value in the range of all numbers, from -32768.0 (0x8000.0000) up to +32767.99999 (0x7fff.ffff).

rnd() called without a max value (nil) returns a random value in the range from 0.0 up to 0.99999 (0x0.ffff).

rnd() appears to accept a max value outside the Pico-8 number range of -32768 to 32767 if the argument is a number literal or literal expression (such as rnd(50000)). The result may overflow the range and be negative.

Examples Edit

print(rnd(20))       -- for example, 3.837
print(flr(rnd(20)))  -- for example, 17

See also Edit