CX Framework
Cross-platform C utility framework
Loading...
Searching...
No Matches
Linear Congruential Generator (LCG)

Macros

#define LCG_MAX   (0x7ffffffe)
 

Functions

int32 lcgRandom (uint32 *state)
 

Detailed Description

A basic linear congruential generator (LCG) using the classic parameters from Numerical Recipes: multiplier 1103515245 and increment 12345.

Characteristics:

When to use:

When NOT to use:

Note
For better random number generation with excellent performance, use the PCG generator instead (see pcg.h).

Example:

uint32 state = 12345; // Simple initialization
int32 val = lcgRandom(&state); // Generate random value [0..LCG_MAX]
int32 lcgRandom(uint32 *state)
Definition lcg.h:68

Macro Definition Documentation

◆ LCG_MAX

#define LCG_MAX   (0x7ffffffe)

Maximum value that can be returned by lcgRandom()

The LCG generates values in the range [0..LCG_MAX] inclusive. This value is 0x7FFFFFFE (2147483646), slightly less than INT32_MAX.

Definition at line 48 of file lcg.h.

Function Documentation

◆ lcgRandom()

int32 lcgRandom ( uint32 *  state)
inline

int32 lcgRandom(uint32 *state)

Generates the next pseudo-random number in the LCG sequence

Updates the state and returns a random integer in the range [0..LCG_MAX]. The state is modified in place using the formula:

state = (state * 1103515245 + 12345) mod (LCG_MAX + 1)

These are the classic LCG parameters used in many implementations including glibc's rand() (though the output transformation may differ).

Important: The state must be initialized to a non-zero value before first use. Different initial values produce different sequences. For simple cases, any non-zero value works; for reproducibility, use a specific seed value.

Parameters
statePointer to the 32-bit state variable (modified in place)
Returns
Random int32 value in range [0..LCG_MAX]

Definition at line 68 of file lcg.h.

References LCG_MAX.