Algorithm for generating pseudo-randomized numbers
A linear congruential generator (LCG) is an algorithm that yields a sequence of pseudo-randomized numbers calculated with a discontinuous piecewise linear equation. The method represents one of the oldest and best-known pseudorandom number generator algorithms. The theory behind them is relatively easy to understand, and they are easily implemented and fast, especially on computer hardware which can provide modular arithmetic by storage-bit truncation.
are integer constants that specify the generator. If c = 0, the generator is often called a multiplicative congruential generator (MCG), or Lehmer RNG. If c ≠ 0, the method is called a mixed congruential generator.[1]: 4-
When c ≠ 0, a mathematician would call the recurrence an affine transformation, not a linear one, but the misnomer is well-established in computer science.[2]: 1
History
The Lehmer generator was published in 1951[3] and the Linear congruential generator was published in 1958 by W. E. Thomson and A. Rotenberg.[4][5]
Period length
A benefit of LCGs is that an appropriate choice of parameters results in a period which is both known and long. Although not the only criterion, too short a period is a fatal flaw in a pseudorandom number generator.[6]
While LCGs are capable of producing pseudorandom numbers which can pass formal tests for randomness, the quality of the output is extremely sensitive to the choice of the parameters m and a.[1][2][7][8][9][10] For example, a = 1 and c = 1 produces a simple modulo-m counter, which has a long period, but is obviously non-random. Other values of ccoprime to m produce a Weyl sequence, which is better distributed but still obviously non-random.
Historically, poor choices for a have led to ineffective implementations of LCGs. A particularly illustrative example of this is RANDU, which was widely used in the early 1970s and led to many results which are currently being questioned because of the use of this poor LCG.[11][8]: 1198–9
There are three common families of parameter choice:
This is the original Lehmer RNG construction. The period is m−1 if the multiplier a is chosen to be a primitive element of the integers modulo m. The initial state must be chosen between 1 and m−1.
One disadvantage of a prime modulus is that the modular reduction requires a double-width product and an explicit reduction step. Often a prime just less than a power of 2 is used (the Mersenne primes 231−1 and 261−1 are popular), so that the reduction modulo m = 2e − d can be computed as (ax mod 2e) + d⌊ax/2e⌋. This must be followed by a conditional subtraction of m if the result is too large, but the number of subtractions is limited to ad/m, which can be easily limited to one if d is small.
If a double-width product is unavailable, and the multiplier is chosen carefully, Schrage's method[12] may be used. To do this, factor m = qa+r, i.e. q = ⌊m/a⌋ and r = m mod a. Then compute ax mod m = a(x mod q) − r⌊x/q⌋. Since x mod q < q ≤ m/a, the first term is strictly less than am/a = m. If a is chosen so that r ≤ q (and thus r/q ≤ 1), then the second term is also less than m: r⌊x/q⌋ ≤ rx/q = x(r/q) ≤ x < m. Thus, both products can be computed with a single-width product, and the difference between them lies in the range [1−m, m−1], so can be reduced to [0, m−1] with a single conditional add.[13]
A second disadvantage is that it is awkward to convert the value 1 ≤ x < m to uniform random bits. If a prime just less than a power of 2 is used, sometimes the missing values are simply ignored.
m a power of 2, c = 0
Choosing m to be a power of two, most often m = 232 or m = 264, produces a particularly efficient LCG, because this allows the modulus operation to be computed by simply truncating the binary representation. In fact, the most significant bits are usually not computed at all. There are, however, disadvantages.
This form has maximal period m/4, achieved if a ≡ ±3 (mod 8) and the initial state X0 is odd. Even in this best case, the low three bits of X alternate between two values and thus only contribute one bit to the state. X is always odd (the lowest-order bit never changes), and only one of the next two bits ever changes. If a ≡ +3, X alternates ±1↔±3, while if a ≡ −3, X alternates ±1↔∓3 (all modulo 8).
It can be shown that this form is equivalent to a generator with modulus m/4 and c ≠ 0.[1]
A more serious issue with the use of a power-of-two modulus is that the low bits have a shorter period than the high bits. Its simplicity of implementation comes from the fact that bits are never affected by higher-order bits, so the low b bits of such a generator form a modulo-2b LCG by themselves, repeating with a period of 2b−2. Only the most significant bit of X achieves the full period.
m a power of 2, c ≠ 0
When c ≠ 0, correctly chosen parameters allow a period equal to m, for all seed values. This will occur if and only if:[1]: 17–19
These three requirements are referred to as the Hull–Dobell Theorem.[14][15]
This form may be used with any m, but only works well for m with many repeated prime factors, such as a power of 2; using a computer's word size is the most common choice. If m were a square-free integer, this would only allow a ≡ 1 (mod m), which makes a very poor PRNG; a selection of possible full-period multipliers is only available when m has repeated prime factors.
Although the Hull–Dobell theorem provides maximum period, it is not sufficient to guarantee a good generator.[8]: 1199 For example, it is desirable for a − 1 to not be any more divisible by prime factors of m than necessary. If m is a power of 2, then a − 1 should be divisible by 4 but not divisible by 8, i.e. a ≡ 5 (mod 8).[1]: §3.2.1.3
Indeed, most multipliers produce a sequence which fails one test for non-randomness or another, and finding a multiplier which is satisfactory to all applicable criteria[1]: §3.3.3 is quite challenging.[8] The spectral test is one of the most important tests.[16]
Note that a power-of-2 modulus shares the problem as described above for c = 0: the low k bits form a generator with modulus 2k and thus repeat with a period of 2k; only the most significant bit achieves the full period. If a pseudorandom number less than r is desired, ⌊rX/m⌋ is a much higher-quality result than X mod r. Unfortunately, most programming languages make the latter much easier to write (X % r), so it is very commonly used.
The generator is not sensitive to the choice of c, as long as it is relatively prime to the modulus (e.g. if m is a power of 2, then c must be odd), so the value c=1 is commonly chosen.
The sequence produced by other choices of c can be written as a simple function of the sequence when c=1.[1]: 11 Specifically, if Y is the prototypical sequence defined by Y0 = 0 and Yn+1 = aYn + 1 mod m, then a general sequence Xn+1 = aXn + c mod m can be written as an affine function of Y:
More generally, any two sequences X and Z with the same multiplier and modulus are related by
In the common case where m is a power of 2 and a ≡ 5 (mod 8) (a desirable property for other reasons), it is always possible to find an initial value X0 so that the denominator X1 − X0 ≡ ±1 (mod m), producing an even simpler relationship. With this choice of X0, Xn = X0 ± Yn will remain true for all n.[2]: 10-11 The sign is determined by c ≡ ±1 (mod 4), and the constant X0 is determined by 1 ∓ c ≡ (1 − a)X0 (mod m).
As a simple example, consider the generators Xn+1 = 157Xn + 3 mod 256 and Yn+1 = 157Yn + 1 mod 256; i.e. m = 256, a = 157, and c = 3. Because 3 ≡ −1 (mod 4), we are searching for a solution to 1 + 3 ≡ (1 − 157)X0 (mod 256). This is satisfied by X0 ≡ 41 (mod 64), so if we start with that, then Xn ≡ X0 − Yn (mod 256) for all n.
For example, using X0 = 233 = 3×64 + 41:
X = 233, 232, 75, 2, 61, 108, ...
Y = 0, 1, 158, 231, 172, 125, ...
X + Y mod 256 = 233, 233, 233, 233, 233, 233, ...
Parameters in common use
The following table lists the parameters of LCGs in common use, including built-in rand() functions in runtime libraries of various compilers. This table is to show popularity, not examples to emulate; many of these parameters are poor. Tables of good parameters are available.[10][2]
As shown above, LCGs do not always use all of the bits in the values they produce. In general, they return the most significant bits. For example, the Java implementation operates with 48-bit values at each iteration but returns only their 32 most significant bits. This is because the higher-order bits have longer periods than the lower-order bits (see below). LCGs that use this truncation technique produce statistically better values than those that do not. This is especially noticeable in scripts that use the mod operation to reduce range; modifying the random number mod 2 will lead to alternating 0 and 1 without truncation.
Contrarily, some libraries use an implicit power-of-two modulus but never output or otherwise use the most significant bit, in order to limit the output to positive two's complement integers. The output is as if the modulus were one bit less than the internal word size, and such generators are described as such in the table above.
LCGs are fast and require minimal memory (one modulo-m number, often 32 or 64 bits) to retain state. This makes them valuable for simulating multiple independent streams. LCGs are not intended, and must not be used, for cryptographic applications; use a cryptographically secure pseudorandom number generator for such applications.
Although LCGs have a few specific weaknesses, many of their flaws come from having too small a state. The fact that people have been lulled for so many years into using them with such small moduli can be seen as a testament to the strength of the technique. A LCG with large enough state can pass even stringent statistical tests; a modulo-264 LCG which returns the high 32 bits passes TestU01's SmallCrush suite,[citation needed] and a 96-bit LCG passes the most stringent BigCrush suite.[35]
For a specific example, an ideal random number generator with 32 bits of output is expected (by the Birthday theorem) to begin duplicating earlier outputs after √m ≈ 216 results. Any PRNG whose output is its full, untruncated state will not produce duplicates until its full period elapses, an easily detectable statistical flaw.[36]
For related reasons, any PRNG should have a period longer than the square of the number of outputs required. Given modern computer speeds, this means a period of 264 for all but the least demanding applications, and longer for demanding simulations.
One flaw specific to LCGs is that, if used to choose points in an n-dimensional space, the points will lie on, at most, n√n!⋅mhyperplanes (Marsaglia's theorem, developed by George Marsaglia).[7] This is due to serial correlation between successive values of the sequence Xn. Carelessly chosen multipliers will usually have far fewer, widely spaced planes, which can lead to problems. The spectral test, which is a simple test of an LCG's quality, measures this spacing and allows a good multiplier to be chosen.
The plane spacing depends both on the modulus and the multiplier. A large enough modulus can reduce this distance below the resolution of double precision numbers. The choice of the multiplier becomes less important when the modulus is large. It is still necessary to calculate the spectral index and make sure that the multiplier is not a bad one, but purely probabilistically it becomes extremely unlikely to encounter a bad multiplier when the modulus is larger than about 264.
Another flaw specific to LCGs is the short period of the low-order bits when m is chosen to be a power of 2. This can be mitigated by using a modulus larger than the required output, and using the most significant bits of the state.
Nevertheless, for some applications LCGs may be a good option. For instance, in an embedded system, the amount of memory available is often severely limited. Similarly, in an environment such as a video game console taking a small number of high-order bits of an LCG may well suffice. (The low-order bits of LCGs when m is a power of 2 should never be relied on for any degree of randomness whatsoever.) The low order bits go through very short cycles. In particular, any full-cycle LCG, when m is a power of 2, will produce alternately odd and even results.
LCGs should be evaluated very carefully for suitability in non-cryptographic applications where high-quality randomness is critical. For Monte Carlo simulations, an LCG must use a modulus greater and preferably much greater than the cube of the number of random samples which are required. This means, for example, that a (good) 32-bit LCG can be used to obtain about a thousand random numbers; a 64-bit LCG is good for about 221 random samples (a little over two million), etc. For this reason, in practice LCGs are not suitable for large-scale Monte Carlo simulations.
Sample code
Python code
The following is an implementation of an LCG in Python, in the form of a generator:
The following is an implementation of an LCG in Haskell utilizing a lazy evaluation strategy to generate an infinite stream of output values in a list:
-- Allowing a generic choice for a, c, m and x_0linearCongruentialGenerator::Integer->Integer->Integer->Integer->[Integer]linearCongruentialGeneratoracmodulusseed=lcgacmx0wherelcgacmx0=seed:map(\x->(a*x+c)%modulus)lcgacmx0-- Specific parameters can be easily specified (eg. Knuth's MMIX parameters):mmixLCG::Integer->[Integer]mmixLCG=linearCongruentialGenerator63641362238467930051442695040888963407(2^(64::Integer))
Free Pascal
Free Pascal uses a Mersenne Twister as its default pseudo random number generator whereas Delphi uses a LCG. Here is a Delphi compatible example in Free Pascal based on the information in the table above. Given the same RandSeed value it generates the same sequence of random numbers as Delphi.
Like all pseudorandom number generators, a LCG needs to store state and alter it each time it generates a new number. Multiple threads may access this state simultaneously causing a race condition. Implementations should use different state each with unique initialization for different threads to avoid equal sequences of random numbers on simultaneously executing threads.
LCG derivatives
There are several generators which are linear congruential generators in a different form, and thus the techniques used to analyze LCGs can be applied to them.
One method of producing a longer period is to sum the outputs of several LCGs of different periods having a large least common multiple; the Wichmann–Hill generator is an example of this form. (We would prefer them to be completely coprime, but a prime modulus implies an even period, so there must be a common factor of 2, at least.) This can be shown to be equivalent to a single LCG with a modulus equal to the product of the component LCG moduli.
Marsaglia's add-with-carry and subtract-with-borrow PRNGs with a word size of b=2w and lags r and s (r > s) are equivalent to LCGs with a modulus of br ± bs ± 1.[37][38]
Multiply-with-carry PRNGs with a multiplier of a are equivalent to LCGs with a large prime modulus of abr−1 and a power-of-2 multiplier b.
A permuted congruential generator begins with a power-of-2-modulus LCG and applies an output transformation to eliminate the short period problem in the low-order bits.
Comparison with other PRNGs
The other widely used primitive for obtaining long-period pseudorandom sequences is the linear-feedback shift register construction, which is based on arithmetic in GF(2)[x], the polynomial ring over GF(2). Rather than integer addition and multiplication, the basic operations are exclusive-or and carry-less multiplication, which is usually implemented as a sequence of logical shifts. These have the advantage that all of their bits are full-period; they do not suffer from the weakness in the low-order bits that plagues arithmetic modulo 2k.[39]
Examples of this family include xorshift generators and the Mersenne twister. The latter provides a very long period (219937−1) and variate uniformity, but it fails some statistical tests.[40]Lagged Fibonacci generators also fall into this category; although they use arithmetic addition, their period is ensured by an LFSR among the least-significant bits.
It is easy to detect the structure of a linear-feedback shift register with appropriate tests[41] such as the linear complexity test implemented in the TestU01 suite; a Boolean circulant matrix initialized from consecutive bits of an LFSR will never have rank greater than the degree of the polynomial. Adding a non-linear output mixing function (as in the xoshiro256** and permuted congruential generator constructions) can greatly improve the performance on statistical tests.
Another structure for a PRNG is a very simple recurrence function combined with a powerful output mixing function. This includes counter mode block ciphers and non-cryptographic generators such as SplitMix64.
A structure similar to LCGs, but not equivalent, is the multiple-recursive generator: Xn = (a1Xn−1 + a2Xn−2 + ··· + akXn−k) mod m for k ≥ 2. With a prime modulus, this can generate periods up to mk−1, so is a useful extension of the LCG structure to larger periods.
A powerful technique for generating high-quality pseudorandom numbers is to combine two or more PRNGs of different structure; the sum of an LFSR and an LCG (as in the KISS or xorwow constructions) can do very well at some cost in speed.
^Lehmer, Derrick H. (1951). "Mathematical methods in large-scale computing units". Proceedings of 2nd Symposium on Large-Scale Digital Calculating Machinery: 141–146.
^L'Ecuyer, Pierre (13 July 2017). Chan, W. K. V.; D'Ambrogio, A.; Zacharewicz, G.; Mustafee, N.; Wainer, G.; Page, E. (eds.). History of Uniform Random Number Generation(PDF). Proceedings of the 2017 Winter Simulation Conference (to appear). Las Vegas, United States. hal-01561551.
^Implementation in glibc-2.26 release. See the code after the test for "TYPE_0"; the GNU C library's rand() in stdlib.h uses a simple (single state) linear congruential generator only in case that the state is declared as 8 bytes. If the state is larger (an array), the generator becomes an additive feedback generator (initialized using minstd_rand0) and the period increases. See the simplified code that reproduces the random sequence from this library.
^Dohmann, Birgit; Falk, Michael; Lessenich, Karin (August 1991). "The random number generators of the Turbo Pascal family". Computational Statistics & Data Analysis. 12 (1): 129–132. doi:10.1016/0167-9473(91)90108-E.
^In spite of documentation on MSDN, RtlUniform uses LCG, and not Lehmer's algorithm, implementations before Windows Vista are flawed, because the result of multiplication is cut to 32 bits, before modulo is applied
Press, WH; Teukolsky, SA; Vetterling, WT; Flannery, BP (2007), "Section 7.1.1. Some History", Numerical Recipes: The Art of Scientific Computing (3rd ed.), New York: Cambridge University Press, ISBN978-0-521-88068-8, archived from the original on 2011-08-11, retrieved 2011-08-10
Gentle, James E., (2003). Random Number Generation and Monte Carlo Methods, 2nd edition, Springer, ISBN0-387-00178-6.
Ban on discussion of slavery in US House In United States history, the gag rule was a series of rules that forbade the raising, consideration, or discussion of slavery in the U.S. House of Representatives from 1836 to 1844. They played a key role in rousing support for ending slavery.[1]: 274 Background Congress regularly received petitions asking for various types of relief or action. Before the gag rules, House rules required that the first thirty days of each sessi...
New World prehistoric projectile Clovis point, 11500–9000 BC, Sevier County, Utah, chert Clovis points are the characteristically fluted projectile points associated with the New World Clovis culture, a prehistoric Paleo-American culture. They are present in dense concentrations across much of North America and they are largely restricted to the north of South America. There are slight differences in points found in the Eastern United States bringing them to sometimes be called Clovis-like....
Bahasa Yunani Puglia Γκραίκο · Γκρίκο Dituturkan diItaliaWilayahPugliaEtnisSuku GrikoPenutur(20.000 jiwa per 1981)[1]40.000 hingga 50,000 sebagai L2 Rumpun bahasaIndo-Eropa HelenikYunaniYunani Attika–Ionia (diperdebatkan) Doria (diperdebatkan)Yunani ItaliaYunani Puglia Sistem penulisanAlfabet Yunani, Alfabet LatinStatus resmiDiakui sebagaibahasa minoritas di Italia PugliaKode bahasaISO 639-3–Glottologapul1237 (Apulian Greek)[2]Lingua...
This article needs additional citations for verification. Please help improve this article by adding citations to reliable sources. Unsourced material may be challenged and removed.Find sources: St. Paul's Cathedral Fond du Lac, Wisconsin – news · newspapers · books · scholar · JSTOR (June 2019) (Learn how and when to remove this message) St. Paul's Cathedral in 2013 St. Paul's Cathedral is the mother church of the Episcopal Diocese of Fond du Lac...
1992 film by Alexandre Rockwell For the British film, see In the Soup (1936 film). In the SoupDirected byAlexandre RockwellWritten byTim KissellAlexandre RockwellProduced byJim StarkHank BlumenthalChosei FunaharaStarring Seymour Cassel Steve Buscemi Jennifer Beals CinematographyPhil ParmetEdited byDana CongdonMusic byMaderDistributed byTriton PicturesRelease dates January 1992 (1992-01) (Sundance) October 23, 1992 (1992-10-23) (New York City) Running time93 mi...
Artikel ini tentang tahun 1912. 1912MileniumMilenium ke-2AbadAbad ke-19Abad ke-20 Abad ke-21Dasawarsa 1890-an1900-an1910-an1920-an1930-anTahun1909191019111912191319141915 1912 (MCMXII) adalah tahun kabisat yang diawali hari Senin dalam kalender Gregorian dan tahun kabisat yang diawali hari Minggu dalam kalender Julian, tahun ke-1912 dalam sebutan Masehi (CE) dan Anno Domini (AD), tahun ke-912 pada Milenium ke-2, tahun ke-12 pada Abad ke-20, dan tahun ke- 3 pada dekade 1910-an. Denom...
For the band, see Home Video (band). For the album by Lucy Dacus, see Home Video (album). For motion pictures made by amateurs, see Home movies. This article needs additional citations for verification. Please help improve this article by adding citations to reliable sources. Unsourced material may be challenged and removed.Find sources: Home video – news · newspapers · books · scholar · JSTOR (April 2021) (Learn how and when to remove this message) Pr...
American college basketball season 2019–20 Northwestern State Demons basketballConferenceSouthland ConferenceRecord15–15 (11–9 Southland)Head coachMike McConathy (21st season)Assistant coaches Jeff Moore Dave Simmons Jacob Spielbauer Home arenaPrather ColiseumSeasons← 2018–192020–21 → 2019–20 Southland Conference men's basketball standings vte Conf Overall Team W L PCT W L PCT Stephen F. Austin 19 – 1 .950 28...
Type of pistol Not to be confused with Machine pistol. A Glock 22 semi-automatic pistol chambered in .40 S&W with a tactical light mounted below its barrel. A semi-automatic pistol (also called a self-loading pistol, autopistol, or autoloading pistol[1]) is a handgun that automatically ejects and loads cartridges in its chamber after every shot fired. Only one round of ammunition is fired each time the trigger is pulled, as the pistol's fire control group disconnects the trigger m...
Professional core of the US Army World War II-era poster advertising a career in the Regular Army The Regular Army of the United States succeeded the Continental Army as the country's permanent, professional land-based military force.[1] In modern times, the professional core of the United States Army continues to be called the Regular Army (often abbreviated as RA). From the time of the American Revolution until after the Spanish–American War, state militias and volunteer regiments...
Spanish Wells DistrikLokasi di BahamaNegara BahamaKelompok pulauRussel IslandLuas • Total26 km2 (10 sq mi)Populasi • Total1.551 • Kepadatan60/km2 (150/sq mi)Kode ISO 3166-2BS-SW Spanish Wells adalah salah satu distrik di Bahama. Kode ISO 3166-2 daerah ini adalah BS-SW. lbsPemerintah daerah di BahamaDistrik tingkat dua Abaco Selatan Abaco Tengah Abaco Utara Andros Selatan Andros Tengah Andros Utara Cat Island Eleuthera Tengah Eleuthe...
System of government Not to be confused with Semi-parliamentary system or Presidential system. World's states coloured by systems of government: Parliamentary systems: Head of government is elected or nominated by and accountable to the legislature Constitutional monarchy with a ceremonial monarch Parliamentary republic with a ceremonial president Parliamentary republic with an executive president Presidential system: Head of government (president) is popul...
This article does not cite any sources. Please help improve this article by adding citations to reliable sources. Unsourced material may be challenged and removed.Find sources: Stump drawing – news · newspapers · books · scholar · JSTOR (December 2009) (Learn how and when to remove this message) For other uses, see Stump (disambiguation). Stump A stump is a cylindrical drawing tool, usually made of soft paper that is tightly wound into a stick and...
Lento/Velocesingolo discograficoScreenshot tratto dal video del branoArtistaTiziano Ferro Pubblicazione21 aprile 2017 Durata3:19 Album di provenienzaIl mestiere della vita Genere[2]Contemporary R&B[1]Neo soulElettropop EtichettaUniversal ProduttoreMichele Canova Iorfida Registrazione2016, Kaneepa Studio, Los Angeles (California) FormatiDownload digitale, 10 CertificazioniDischi di platino Italia (2)[3](vendite: 100 000+) Tiziano Ferro - cron...
محتوى هذه المقالة بحاجة للتحديث. فضلًا، ساعد بتحديثه ليعكس الأحداث الأخيرة وليشمل المعلومات الموثوقة المتاحة حديثًا. يفتقر محتوى هذه المقالة إلى الاستشهاد بمصادر. فضلاً، ساهم في تطوير هذه المقالة من خلال إضافة مصادر موثوق بها. أي معلومات غير موثقة يمكن التشكيك بها وإزالت�...