Random Numbers in AngelScript

import math;
import string;

void main()
{
    // For example, random() returns a random float between 0 and 1
    print(int(random() * 100) + "," + int(random() * 100) + "\n");

    // random() returns a float f, 0.0 <= f < 1.0
    print(random() + "\n");

    // This can be used to generate random floats in
    // other ranges, for example 5.0 <= f' < 10.0
    print((random() * 5 + 5) + "," + (random() * 5 + 5) + "\n");

    // If you want a known seed, you can use srand()
    // to set the random number generator seed
    srand(42);
    print(int(random() * 100) + "," + int(random() * 100) + "\n");

    // Using the same seed will produce the same sequence of random numbers
    srand(42);
    print(int(random() * 100) + "," + int(random() * 100) + "\n");
}

AngelScript’s math module provides pseudorandom number generation.

The random() function in AngelScript returns a float between 0 and 1. We can use this to generate random integers and floats in different ranges.

To generate a random integer between 0 and 99, we multiply the result of random() by 100 and cast it to an integer.

We can generate random floats in custom ranges by scaling and shifting the result of random(). For example, to get a float between 5 and 10, we multiply by 5 (to get a range of 0 to 5) and then add 5.

AngelScript uses srand() to set the random number generator seed. This allows you to generate reproducible sequences of random numbers, which can be useful for testing or when you need consistent randomness.

Here’s an example of what the output might look like:

68,56
0.8090228139659177
5.840125017402497,6.937056298890035
94,49
94,49

Note that some of the generated numbers may be different when you run the sample, except for the last two lines which use a fixed seed.

AngelScript’s random number generation capabilities are somewhat simpler compared to some other languages, but they cover the basic needs for most applications requiring randomness.