Fandom

Pico-8 Wiki

Rnd

162pages on
this wiki
Add New Page
Comments0 Share
rnd( max )

Generates a random number between 0 and the given maximum.

max
The maximum of the range.

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 to 32767.0.

rnd() called without a max value (nil) returns a random value in the range from 0.0 to 1.0.

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

Ad blocker interference detected!


Wikia is a free-to-use site that makes money from advertising. We have a modified experience for viewers using ad blockers

Wikia is not accessible if you’ve made further modifications. Remove the custom ad blocker rule(s) and the page will load as expected.