Random numbers
std/random.mox makes random numbers. It is not a part of std.mox, so import it too:
import "std.mox";
import "std/random.mox";
Numbers from 0 to 1
a := random_f32(); // 0.601263
b := random_f64(); // 0.7477740925472398
Both return a number from 0 up to 1. They never return 1 itself.
Numbers in a range
dice := random_in_range(1i32, 6i32); // 1, 2, 3, 4, 5 or 6
speed := random_in_range(0.5f, 2.0f);
byte := random_in_range(0u8, 255u8);
random_in_range(min, max) works on all integer and float types. Both arguments must have the same type.
- For integers
maxis included. Each value has the same chance. - For floats the result never reaches
max. - If
maxis not bigger thanmin, an integer range returnsmin.
Vectors
random_in_range also takes arrays. Each element gets its own range:
pos := random_in_range(vec2f.{ 0, 0 }, vec2f.{ 800, 600 });
color := random_in_range([4]u8.{ 0, 0, 0, 255 }, [4]u8.{ 255, 255, 255, 255 });
Here color has random red, green and blue, and alpha is always 255.
Seed
The numbers are not truly random. They are computed from a start value, the seed. The same seed gives the same numbers, so the program above prints the same values on each run.
To get new numbers on each run, set the seed from the clock once at the start:
prng_reset_default(time_unix_ms().cast(u64));
A fixed seed is useful too. A level made from seed 42 is the same level each time, and a test with a fixed seed fails the same way each time.
Your own generator
All functions above use the default generator. You can make your own PRng and pass a pointer to it as the last argument:
rng := prng_seed(42);
x := random_f32(rng.^);
d := random_in_range(1i32, 6i32, rng.^);
Each generator has its own state. Use one for level generation and another one for particles, and the level stays the same no matter how many particles you spawn.
The default generator is thread local. Each thread has its own one, and each starts from seed 0 until you call prng_reset_default on that thread.
Raw values
These functions always need a generator. Pass prng_default() to use the default one.
raw := next_u64(rng.^); // any u64
idx := next_below(rng.^, 10); // 0 to 9
next_below(rng, n) is handy to pick an item of an array:
names := [3][]u8.{ "red", "green", "blue" };
name := names[next_below(prng_default(), 3)];
There are also next_u128, and next_upto_u64(rng, n) that returns 0 to n with n included.
Not for secrets
The generator is xoshiro256**. It is fast and good for games and simulations. Do not use it for passwords, keys or tokens: the next numbers can be guessed from the previous ones.