Subtract-with-carry (SWC) is a pseudorandom number generator created by George Marsaglia and Arif Zaman in 1991. It falls into a class of generators known as lagged Fibonacci generators, where each new number in the sequence is a function of two previous numbers at fixed distances ("lags"). SWC is one of three random number generator engines included in the standard C++11 library. It belongs to a family of generators that also includes add-with-carry and subtract-with-borrow engines.
Algorithm The subtract-with-carry algorithm's state is defined by a list of R numbers and a "carry" value, where R is the "long lag". The initial values for this state, known as the "seed," can be chosen arbitrarily. To generate the next number in the sequence, the algorithm uses two values from its state list: the value at the "short lag" position (S steps ago) and the value at the "long lag" position (R steps ago). The new number is calculated by subtracting the long-lag value and the current carry bit from the short-lag value. If this subtraction results in a negative number (a "borrow"), the result is adjusted by adding a large constant M (the modulus), and the carry for the next step is set to 1. Otherwise, the carry is set to 0. The newly generated number replaces the oldest number in the list, and the process repeats.
Example A simple example can illustrate the process. Let the parameters be:
Modulus M = 10 Long lag R = 3 Short lag S = 1 Initial state (seed): a list of 3 numbers x = ( x 0 , x 1 , x 2 ) = ( 6 , 8 , 3 ) {\displaystyle x=(x_{0},x_{1},x_{2})=(6,8,3)} and an initial carry c 2 = 0 {\displaystyle c_{2}=0} . To generate the next number, x 3 {\displaystyle x_{3}} :
Identify the short-lag value x 3 − S = x 2 = 3 {\displaystyle x_{3-S}=x_{2}=3} and the long-lag value x 3 − R = x 0 = 6 {\displaystyle x_{3-R}=x_{0}=6} . Perform the subtraction: x 2 − x 0 − c 2 {\displaystyle x_{2}-x_{0}-c_{2}} → 3 − 6 − 0 = − 3 {\displaystyle 3-6-0=-3} . Since the result is negative, a borrow occurs. The new carry c 3 {\displaystyle c_{3}} becomes 1. The new number x 3 {\displaystyle x_{3}} is the result modulo M: − 3 mod 10 = 7 {\displaystyle -3\mod 10=7} . The state is updated. The list becomes ( x 1 , x 2 , x 3 ) = ( 8 , 3 , 7 ) {\displaystyle (x_{1},x_{2},x_{3})=(8,3,7)} , and the carry is now 1 for the next step. This process can be repeated to generate a long sequence of pseudorandom numbers.
Formal definition The sequence generated by the subtract-with-carry engine is described by the recurrence relation:
x ( i ) = ( x ( i − S ) − x ( i − R ) − c y ( i − 1 ) ) mod M {\displaystyle x(i)=(x(i-S)-x(i-R)-cy(i-1))\ {\bmod {\ }}M}
where the new carry, c y ( i ) {\displaystyle cy(i)} , is defined as:
c y ( i ) = { 1 , if x ( i − S ) − x ( i − R ) − c y ( i − 1 ) < 0 0 , otherwise {\displaystyle cy(i)={\begin{cases}1,&{\text{if }}x(i-S)-x(i-R)-cy(i-1)<0\\0,&{\text{otherwise}}\end{cases}}}
… excerpt ends here. Continue reading the full article.
