Skip to main content

math.rand()

Returns a random number

Availability

Device + Agent

Returns

Integer — the generated random number

Description

This function returns a random number between zero and the system constant RAND_MAX. In the case of imp001 through imp004m, the generated value is the output of the host STMicroelectronics SM32 SoC’s high-quality random number generation hardware, which has passed National Institute of Standards and Technology SP800-22b tests. It is effectively a true random number generator.

On the imp005, which is based on a Broadcom SoC, math.rand() instead uses a pseudorandom generator fed with entropy from a conventional collection of timing-related and phase-related sources.

The number returned by math.rand() is an integer. Since RAND_MAX is also an integer, dividing the returned number by RAND_MAX in order to deliver random numbers within a different range will yield truncation errors: the result will be 0 or, occasionally, 1.

To avoid this, force Squirrel to perform the division using floating-point math; you do this by placing 1.0 * at the start of the sum, as the example code shows below.

The parallel function math.srand(), used to set the random number generator’s seed, can be added to both agent and device code but has no effect. The random number generator is automatically seeded correctly on startup for both imps and agents.

Example Code