On Xorshift random number generator algorithm
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
The Xorshift random number generator (RNG) is a family of pseudorandom number generating algorithms that are designed to be both fast and efficient. Suitable for simulations, simple games, and randomized algorithms, Xorshift generators are a subset of linear-feedback shift register (LFSR) algorithms. Introduced by George Marsaglia in 2003, the Xorshift family attempts to pack simplicity and speed into a lightweight RNG suitable for applications that do not require cryptographic security.
Technical Overview
The essence of the Xorshift algorithm is the use of bitwise exclusive OR (XOR) operations, bit shifts, and sometimes mixing transformations to produce pseudorandom sequences from an initial "seed" value. The algorithm's operation can be broken down into three main steps:
Algorithm Steps
- Initialization:
- Choose an initial seed `x` that serves as the starting state. The quality of randomness can be influenced by this seed, so it is often chosen using the current timestamp or other entropy sources.
- Bitwise Operations:
- Utilize XOR and shift operations to permute the bits of the state. The basic formula employed in a 32-bit version, for example, might look something like this:
- Here, `a`, `b`, and `c` are chosen shift amounts; they are constants that determine the state transformation.
- Extract the final state as the pseudorandom number and use it as the seed for the next iteration.
- Speed: Xorshift operations execute very swiftly due to their reliance on primary bitwise operations, making them highly attractive in performance-sensitive applications.
- Simplicity: The algorithm involves minimal lines of code and compact logic, allowing easy implementation.
- Statistical Bias: The simplicity can result in noticeable statistical biases and artifacts if parameters are not properly chosen.
- Period Length: Though the cycle length is substantial, it can be much shorter compared to more sophisticated generators like Mersenne Twister when not configured correctly.
- Lack of Cryptographic Security: Xorshift is unsuitable for security applications as output sequences can be predictable or reversible given enough knowledge of the state and parameters.
- Simulations: Especially Monte Carlo methods where computational overhead needs to be minimal.
- Game Development: For procedural generation and random event handling that doesn't require secure randomness.
- Sample Shuffling: Applications requiring quick shuffling of elements.

