Random Numbers¶
You may already know about the rand
function in C to generate random numbers. This is a great starting point, as it returns a random number from 0 to RAND_MAX
. However, there's no guarantee the quality of the random numbers is any good, and also refers to global state, meaning you can only have a single random number generator. Instead, CF provides it's own method for generating random numbers that overcomes these issues.
Seeding¶
To initialize a fresh random number generator, CF_Rnd
, call cf_rnd_seed
.
The seed acts as the initial parameter for the random number genertor, and dictates what number sequence will be generated. Each seed produces a deterministic set of numbers. That means if ever need to recreate something generated from random numbers, you can use the same initial seed.
If we want to generate seemingly random but different numbers each time the application is started up, a great way is to query the system's time. In C there's a function called time
that returns an integer representing the number of seconds elapsed since the epoch. You may typecast the return value to an integer and pass it into cf_rnd_seed
.
CF_Rnd
only takes up 128 bytes of stack space, so feel free to create as many of them as you need!
Random Numbers¶
CF_Rnd
can generate random integers and floats, and also generate them within specified ranges. For example, you can make a function to return a random float from 0 to 1: