FANDOM


rnd( [max] )
Generates a random number between 0 and the given maximum.
max
The range, non-inclusive. Defaults to 1.

The rnd() function returns a random number in a range. The result ranges from 0 up the given max, but will never be the max value itself. For instance, rnd(10) can return from 0 up to 9.99999, but will never return 10.

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

If max is not supplied, it will default to 1. Values returned will range from 0.0 up to 0.99999 (0x0.ffff).

The random number generator is initialized with an unpredictable seed value when PICO-8 starts. The generator may be initialized with an explicit seed using srand(), which permits a program to execute multiple times and always receive the same sequence of random numbers.

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:

scale    = rnd(20) - 10     -- a random number between -10 and 10
bomb.x   = 32 + rnd(64)     -- a random number between 32 and 96
die_roll = 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

Undocumented range 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() appears to treat the max value as if it were unsigned. For instance, calling rnd(-1) causes the randomizer to act internally as if the call had been rnd(65535). The random number is generated in this unsigned range. Therefore, since values 32768..65535 in unsigned format represent -32768..-1 in signed format, it should be expected that some return values will be negative in this case.

This extra range is not normally useful, but a max value of 0xffff.ffff will produce almost a full 32 bits of randomness in a single call to rnd(), distributed across both the integer and fractional bits. However, because rnd() never returns the actual max value, it's only possible to get results from 0x0000.0000 to 0xffff.fffe.

If true 32-bit randomness is needed, it may be obtained by calling rnd() twice and combining the two results:

function rnd32()
  return rnd() << 16 | rnd()
end

Examples Edit

print(rnd(20))       -- for example, 3.837
 
print(flr(rnd(20)))  -- for example, 17
 
-- note this is the same as rnd(0xffff)
print(rnd(-1))       -- for example, -1734.56 or 13744.63

See also Edit

Community content is available under CC-BY-SA unless otherwise noted.