Multiply-with-carry pseudorandom number generator

In computer science, multiply-with-carry (MWC) is a method invented by George Marsaglia for generating sequences of random integers based on an initial set from two to many thousands of randomly chosen seed values. The main advantages of the MWC method are that it invokes simple computer integer arithmetic and leads to very fast generation of sequences of random numbers with immense periods, ranging from around $$2^{60}$$ to $$2^{2000000}$$.

As with all pseudorandom number generators, the resulting sequences are functions of the supplied seed values.

General theory
An MWC generator is a special form of Lehmer random number generator $$x_n = bx_{n-1} \bmod p$$ which allows efficient implementation of a prime modulus $$p$$ much larger than the machine word size.

Normal Lehmer generator implementations choose a modulus close to the machine word size. An MWC generator instead maintains its state in base $$b$$, so multiplying by $$b$$ is done implicitly by shifting one word. The base $$b$$ is typically chosen to equal the computer's word size, as this makes arithmetic modulo $$b$$ trivial. This may vary from $$b = 2^8$$ for a microcontroller to $$b = 2^{64}$$. (This article uses $$b = 2^{32}$$ for examples.)

The initial state ("seed") values are arbitrary, except that they must not be all zero, nor all at the maximum permitted values ($$x_0 = b-1$$ and $$c_0 = a-1$$ ). (This is commonly done by choosing $$c_0$$ between 1 and $$a-2$$.). The MWC sequence is then a sequence of pairs $$x_n, c_n$$ determined by


 * $$x_n=(ax_{n-1}+c_{n-1})\,\bmod\,b,\ c_n=\left\lfloor\frac{ax_{n-1}+c_{n-1}}{b}\right\rfloor$$

This is called a lag-1 MWC sequence. Sometimes an odd base is preferred, in which case $$b = 2^k-1$$ can be used, which is almost as simple to implement. A lag-$$r$$ sequence is a generalization of the lag-1 sequence allowing longer periods. The lag-$$r$$ MWC sequence is then a sequence of pairs $$x_n, c_n$$ (for $$n > r$$) determined by


 * $$x_n=(ax_{n-r}+c_{n-1})\,\bmod\,b,\ c_n=\left\lfloor\frac{ax_{n-r}+c_{n-1}}{b}\right\rfloor$$

and the MWC generator output is the sequence of $$x$$'s,
 * $$x_r, x_{r+1}, x_{r+2}, ...$$

In this case, the initial state ("seed") values must not be all zero nor $$x_0 = b-1$$ and $$c_{r-1} = a-1$$.

The MWC multiplier $$a$$ and lag $$r$$ determine the modulus $$p = ab^r-1$$. In practice, $$a$$ is chosen so the modulus is prime and the sequence has long period. If the modulus is prime, the period of a lag-$$r$$ MWC generator is the order of $$b$$ in the multiplicative group of numbers modulo $$p$$. While it is theoretically possible to choose a non-prime modulus, a prime modulus eliminates the possibility of the initial seed sharing a common divisor with the modulus, which would reduce the generator's period.

Because 2 is a quadratic residue of numbers of the form $$8k \pm 1$$, $$b = 2^k$$ cannot be a primitive root of $$p = ab^r-1$$. Therefore, MWC generators with base $$2^k$$ have their parameters chosen so their period is (abr−1)/2. This is one of the difficulties that use of b = 2k − 1 overcomes.

The basic form of an MWC generator has parameters a, b and r, and r+1 words of state. The state consists of r residues modulo b
 * 0 ≤ x0, x1, x2,..., xr−1 < b,

and a carry cr−1 &lt; a.

Although the theory of MWC generators permits a &gt; b, a is almost always chosen smaller for convenience of implementation.

The state transformation function of an MWC generator is one step of Montgomery reduction modulo p. The state is a large integer with most significant word cn−1 and least significant word xn−r. Each step, xn−r·(abr−1) is added to this integer. This is done in two parts: −1·xn−r is added to xn−r, resulting in a least significant word of zero. And second, a·xn−r is added to the carry. This makes the integer one word longer, producing two new most significant words xn and cn.

So far, this has simply added a multiple of p to the state, resulting in a different representative of the same residue class modulo p. But finally, the state is shifted down one word, dividing by b. This discards the least significant word of zero (which, in practice, is never computed at all) and effectively multiplies the state by b−1 (mod p).

Thus, a multiply-with-carry generator is a Lehmer generator with modulus p and multiplier b−1 (mod p). This is the same as a generator with multiplier b, but producing output in reverse order, which does not affect the quality of the resultant pseudorandom numbers.

Couture and L'Ecuyer have proved the surprising result that the lattice associated with a multiply-with-carry generator is very close to the lattice associated with the Lehmer generator it simulates. Thus, the mathematical techniques developed for Lehmer generators (such as the spectral test) can be applied to multiply-with-carry generators.

Efficiency
A linear congruential generator with base b = 232 is implemented as
 * $$x_{n+1}=(ax_n+c)\ \bmod\,2^{32},$$

where c is a constant. If a ≡ 1 (mod 4) and c is odd, the resulting base-232 congruential sequence will have period 232.

This can be computed using only the low 32 bits of the product of a and the current x. However, many microprocessors can compute a full 64-bit product in almost the same time as the low 32 bits. Indeed, many compute the 64-bit product and then ignore the high half.

A lag-1 multiply-with-carry generator allows us to make the period nearly 263 by using almost the same computer operations, except that the top half of the 64-bit product is not ignored after the product is computed. Instead, a 64-bit sum is computed, and the top half is used as a new carry value c rather than the fixed additive constant of the standard congruential sequence: Compute ax+c in 64 bits, then use the top half as the new c, and bottom half as the new x.

Choice of multiplier
With multiplier a specified, each pair of input values x, c is converted to a new pair,


 * $$x\leftarrow (ax+c)\,\bmod\,2^{32},\ \ c\leftarrow \left\lfloor\frac{ax+c}{2^{32}}\right\rfloor.$$

If x and c are not both zero, then the period of the resulting multiply-with-carry sequence will be the order of b = 232 in the multiplicative group of residues modulo abr − 1, that is, the smallest n such that bn ≡ 1 (mod abr − 1).

If p = abr − 1 is prime, then Fermat's little theorem guarantees that the order of any element must divide p − 1 = abr − 2, so one way to ensure a large order is to choose a such that p is a "safe prime", that is both p and (p − 1)/2 = abr/2 − 1 are prime. In such a case, for b= 232 and r = 1, the period will be abr/2 − 1, approaching 263, which in practice may be an acceptably large subset of the number of possible 32-bit pairs (x, c).

More specifically, in such a case, the order of any element divides p − 1, and there are only four possible divisors: 1, 2, abr/2 − 1, or abr − 2. The first two apply only to the elements 1 and −1, and quadratic reciprocity arguments show that the fourth option cannot apply to b, so only the third option remains.

Following are some maximal values of a for computer applications which satisfy the above safe prime condition, for lag-1 generators:

<!-- Some more, if anyone wants: ? maxsafeprime(64,32) \\ lag-2 -4222 4294963074 39614042316055429195908513791 ? maxsafeprime(128,32) \\ lag-4 -5521 4294961775 730749879315977573851214025712537694431818547199 ? maxsafeprime(128,64) \\ lag-2 -4057 18446744073709547559 3138550867693339691655113412480160072595786546890200317951 ? maxsafeprime(256,32) \\ lag-8 -22807 4294944489 248660297769803703342456611381682873477670870634403724088059964492020514268892838756351 ? maxsafeprime(256,64) \\ lag-4 -21466 18446744073709530150 1067993517960453798401017068970050576113970162931011395826775387590936027392071118079860618035199 ? maxsafeprime(512,32) \\ lag-16 -67063 4294900233 28792598701164853979792802082771056557436637982777253258006290527115210359966947958901407759016872502237208239751280948631518700106842009223244338317635401163997183 ? maxsafeprime(512,64) \\ lag-8 -26086 18446744073709525530 123665200736552092152212430268529625273557622951754879243663130059861786904854023122189956281348304067952364722086662308590156190815814319471879561331834772624219399719485439 ? maxsafeprime(1024,32) \\ lag-32 -342523 4294624773 386020873561586592074312812522001851875274492595466457251272730611699635012941082972544756647960056099096146138538415983914543911174668233250385795466842403122622602773225563630137131067198828737446415628624118888350116673947397380305414998889062040317435675434112752838821870310259311800378970489743273380296192425983 ? maxsafeprime(1024,64) \\ lag-16 -152947 18446744073709398669 1658079259093474837955046990989813605647917294419555600143486010512540342085706465869156251304268794682832026731777412049076520831664483243035188343024949666509083731849181029064715081772539350969645500928870083606320829031526419342763296573142748690249657038997521828687436494817689824137958118622243245482394468296933351882751 ? maxsafeprime(2048,32) \\ lag-64 -1749331 4293217965 69371975520183243822837632971278774856132795479963488742706318105552227461308599472167060693836765045724389558824030269595037151601383880507414964542078695818449372423504269991748368637137720087498466622142976226949894222824351525908961377017655342894351812985614998321172518146432497632380597797298854096266029258649761736536128160679625525193903755023032720248557704312209315766210756914099716950140053001234861530530470624087454335210719938647927313602780385238554702492456709577138556090790697041120625025891146398536158939286917009857603714093126373277598762864327152198316564372746624350294958143976955590611549311467519 time = 3min, 40,326 ms. ? maxsafeprime(2048,64) \\ lag-32 -332116 18446744073709219500 298071770112990595075757018580978828533608570182393883969695435903079275381608290209678233651762705213235666843932624307449818244274650520216029820130416772033982119613360882096743826673135638907502306566491761156503684445718874265540350778839560442913813248433348212305532331813493525835522564261912018620160726293562134908776979459110820699918337349980978809892711019892989688428080233423943299299553034323044182299930806193772627242438760165350131715351846812909177033297376337943631962139503149756400280910165255374105421571036754611380470994838686293814993994238634318615715024647997514398437529479730014419868867795105397866495999 time = 2min, 47,322 ms. ? maxsafeprime(4096,32) \\ lag-128 -3674707 4291292589 [redacted, 2.240889e1242] time = 1h, 30min, 1,146 ms. ? maxsafeprime(4096,64) \\lag-64 -5098417 18446744073704453199 [redacted, 9.632787e1251] time = 2h, 18min, 8,085 ms. maxsafeprime(8192,32) \\ lag-256 -31313656 4263653640 [redacted, 2.325286e2475] time = 59h, 20min, 50,916 ms. -->

While a safe prime ensures that almost any element of the group has a large order, the period of the generator is specifically the order of b. For small moduli, more computationally expensive methods can be used to find multipliers a where the period is ab/2 − 1. The following are again maximum values of a of various sizes.

MWC generators as repeating decimals
The output of a multiply-with-carry generator is equivalent to the radix-b expansion of a fraction with denominator p = abr − 1. Here is an example for the simple case of b = 10 and r = 1, so the result is a repeating decimal.

Starting with $c_0=1,x_0=0$, the MWC sequence


 * $$x_n=(7x_{n-1}+c_{n-1})\,\bmod\,10,\ c_n=\left\lfloor\frac{7x_{n-1}+c_{n-1}}{10}\right\rfloor,$$

produces this sequence of states:
 * 10,01,07,49,67,55,40,04,28,58,61,13,22,16,43,25,37,52,19,64,34,31, 10,01,07,...

with period 22. Consider just the sequence of ''xi:
 * 0,1,7,9,7,5,0,4,8,8,1,3,2,6,3,5,7,2,9,4,4,1, 0,1,7,9,7,5,0,...

Notice that if those repeated segments of x values are put in reverse order:
 * $$1449275\cdots 9710\,1449275\cdots 9710\,144\cdots$$

we get the expansion j/(ab−1) with a=7, b=10, j=10:


 * $$\frac{10}{69}=0.1449275362318840579710\,14492753623\ldots$$

This is true in general: The sequence of xs produced by a lag-r MWC generator:


 * $$ x_n=(ax_{n-r}+c_{n-1})\bmod\,b\,,\ \ c_n=\left\lfloor\frac{ax_{n-r}+c_{n-1}}{b}\right\rfloor,$$

when put in reverse order, will be the radix-b expansion of a fraction j/(abr &minus; 1) for some 0 < j < abr.

Equivalence to linear congruential generator
Continuing the above example, if we start with $x_0=34$, and generate the ordinary congruential sequence
 * $$x_n=7x_{n-1}\,\bmod\,69$$,

we get the period 22 sequence
 * 31,10,1,7,49,67,55,40,4,28,58,61,13,22,16,43,25,37,52,19,64,34, 31,10,1,7,...

and that sequence, reduced mod 10, is
 * 1,0,1,7,9,7,5,0,4,8,8,1,3,2,6,3,5,7,2,9,4,4, 1,0,1,7,9,7,5,0,...

the same sequence of x's resulting from the MWC sequence.

This is true in general, (but apparently only for lag-1 MWC sequences):

Given initial values $$x_0,c_0$$, the sequence $$x_1,x_2,\ldots$$ resulting from the lag-1 MWC sequence


 * $$x_n=(ax_{n-1}+c_{n-1})\,\bmod b\,,\ \ c_n=\left\lfloor\frac{ax_{n-1}+c_{n-1}}{b}\right\rfloor$$

is exactly the Lehmer random number generator output sequence yn = ayn &minus; 1 mod (ab &minus; 1), reduced modulo b.

Choosing a different initial value y0 merely rotates the cycle of x's.

Complementary-multiply-with-carry generators
Establishing the period of a lag-r MWC generator usually entails choosing multiplier a so that p = abr − 1 is prime. Then p − 1 will have to be factored in order to find the order of b mod p. If p is a safe prime, then this is simple, and the order of b will be either p − 1 or (p − 1)/2. In other cases, p &minus; 1 may be difficult to factor.

However, the algorithm also permits a negative multiplier. This leads to a slight modification of the MWC procedure, and produces a modulus p = $$ = abr + 1. This makes p − 1 = abr easy to factor, making it practical to establish the period of very large generators.

The modified procedure is called complementary-multiply-with-carry (CMWC), and the setup is the same as that for lag-r MWC: multiplier a, base b, and r + 1 seeds,


 * x0, x1, x2, ..., xr−1, and cr−1.

The modification is to the generation of a new pair (x, c). Rearranging the computation to avoid negative numbers, the new x value is complemented by subtracting it from b − 1:
 * $$x_n=(b-1)-(ax_{n-r}+c_{n-1})\,\bmod\,b,\ c_n=\left\lfloor\frac{ax_{n-r}+c_{n-1}}{b}\right\rfloor.$$

The resulting sequence of xs produced by the CMWC RNG will have period the order of b in the multiplicative group of residues modulo abr+1, and the output xs, in reverse order, will form the base b expansion of j/(abr+1) for some 0 < j < abr.

Use of lag-r CMWC makes it much easier to find periods for rs as large as 512, 1024, 2048, etc. (Making r a power of 2 makes it slightly simpler to access elements in the array containing the r most recent xs.)

Another advantage of this modified procedure is that the period is a multiple of b, so the output is exactly equidistributed mod b. (The ordinary MWC, over its full period, produces each possible output an equal number of times except that zero is produced one time less, a bias which is negligible if the period is long enough.)

One disadvantage of the CMWC construction is that, with a power-of-two base, the maximum achievable period is less than for a similar-sized MWC generator; you lose several bits. Thus, an MWC generator is usually preferable for small lags. This can remedied by using b = 2k−1, or choosing a lag one word longer to compensate.

Some examples: With b = 232, and a = 109111 or 108798 or 108517, the period of the lag-1024 CMWC
 * $$x_n=(b-1)-(ax_{n-1024}+c_{n-1})\,\bmod\,b,\ c_n=\left\lfloor\frac{ax_{n-1024}+c_{n-1}}{b}\right\rfloor.$$

will be a·232762 = ab1024/64, about 109867.

With b = 232 and a = 3636507990, p = ab1359 − 1 is a safe prime, so the MWC sequence based on that a has period 3636507990·243487 ≈ 1013101.

With b = 232, a CMWC RNG with near record period may be based on the prime p = 15455296b42658 + 1. The order of b for that prime is 241489·21365056 ≈ 10410928.

More general moduli
The MWC modulus of abr−1 is chosen to make computation particularly simple, but brings with it some disadvantages, notably that the period is at most half the modulus. There are several ways to generalize this, at the cost of more multiplications per iteration.

First, it is possible to add additional terms to the product, producing a modulus of the form arbr+asbs−1. This requires computing cnb + xn = arxn−r + asxn−s. (The carry is limited to one word if ar + as ≤ b.)

However, this does not fix the period issue, which depends on the low bits of the modulus. Fortunately, the Montgomery reduction algorithm permits other moduli, as long as they are relatively prime to the base b, and this can be applied to permit a modulus of the form arbr−a0, for a wide range of values a0. Goresky and Klapper developed the theory of these generalized multiply-with-carry generators, proving, in particular, that choosing a negative a0 and ar–a0 &lt; b the carry value is always smaller than b, making the implementation efficient. The more general form of the modulus improves also the quality of the generator, albeit one cannot always get full period.

To implement a Goresky-Klapper generator one precomputes a$$ (mod b), and changes the iteration as follows:
 * $$t = c_{n-1} + \sum_1^r a_i x_{n-i},

\ x_n = a_0^{-1}t \bmod b, \ c_n = \left\lfloor\frac{t - a_0 x_n}{b}\right\rfloor.$$

In the common case that b = 2k, a0 must be odd for the inverse to exist.

Implementation
The following is an implementation of the CMWC algorithm in the C programming language. Also, included in the program is a sample initialization function. In this implementation the base is 232&minus;1 and lag r=4096. The period of the resulting generator is about $$2^{131104}$$.

The following are implementations of small-state MWC generators with 64-bit output using 128-bit multiplications.

The following are implementations of small-state Goresky-Klapper's generalized MWC generators with 64-bit output using 128-bit multiplications.

Usage
Because of simplicity and speed, CMWC is known to be used in game development, particularly in modern roguelike games. It is informally known as the Mother of All PRNGs, a name originally coined by Marsaglia himself. In libtcod, CMWC4096 replaced MT19937 as the default PRNG.