Linear congruential generator: Difference between revisions

Added Easylang
(Added Easylang)
 
(48 intermediate revisions by 24 users not shown)
Line 1:
{{task|Randomness}}
The [[wp:linear congruential generator|linear congruential generator]] is a very simple example of a [[random number generator]]. All linear congruential generators use this formula:
 
All linear congruential generators use this formula:
* <math>r_{n + 1} = a \times r_n + c \pmod m</math>
 
Where:
 
Where:
* <math>r_0</math> is a seed.
* <math>r_1</math>, <math>r_2</math>, <math>r_3</math>, ..., are the random numbers.
* <math>a</math>, <math>c</math>, <math>m</math> are constants.
 
 
If one chooses the values of <math>a</math>, <math>c</math> and <math>m</math> with care, then the generator produces a uniform distribution of integers from <math>0</math> to <math>m - 1</math>.
Line 18 ⟶ 20:
In these formulas, the seed becomes <math>state_0</math>. The random sequence is <math>rand_1</math>, <math>rand_2</math> and so on.
 
BSD formula:
 
;BSD formula:
* <math>state_{n + 1} = 1103515245 \times state_n + 12345 \pmod{2^{31}}</math>
* <math>rand_n = state_n</math>
* <math>rand_n</math> is in range 0 to 2147483647.
 
Microsoft formula:
 
;Microsoft formula:
* <math>state_{n + 1} = 214013 \times state_n + 2531011 \pmod{2^{31}}</math>
* <math>rand_n = state_n \div 2^{16}</math>
* <math>rand_n</math> is in range 0 to 32767.
 
 
The BSD formula was so awful that FreeBSD switched to a different formula. More info is at [[Random number generator (included)#C]].
The BSD formula was so awful that FreeBSD switched to a different formula.
 
More info is at [[Random number generator (included)#C]].
<br><br>
 
=={{header|11l}}==
<syntaxhighlight lang="11l">T LinearCongruentialGenerator
seed = 0
Int a, c, m
 
F (a, c, m)
.a = a
.c = c
.m = m
 
F ()()
.seed = (.a * .seed + .c) [&] .m
R .seed
 
V bsd_rnd = LinearCongruentialGenerator(1103515245, 12345, 7FFF'FFFF)
V ms_rnd = LinearCongruentialGenerator(214013, 2531011, 7FFF'FFFF)
 
print(‘BSD RAND:’)
L 5
print(bsd_rnd())
print()
print(‘MS RAND:’)
L 5
print(ms_rnd() >> 16)</syntaxhighlight>
 
{{out}}
<pre>
BSD RAND:
12345
1406932606
654583775
1449466924
229283573
 
MS RAND:
38
7719
21238
2437
8855
</pre>
 
=={{header|360 Assembly}}==
<langsyntaxhighlight lang="360asm">* Linear congruential generator 07/03/2017
LINCONG CSECT
USING LINCONG,R12
Line 70 ⟶ 118:
XDEC DS CL12
YREGS
END LINCONG</langsyntaxhighlight>
{{out}}
<pre>
Line 89 ⟶ 137:
We first specify a generic package LCG:
 
<langsyntaxhighlight Adalang="ada">generic
type Base_Type is mod <>;
Multiplyer, Adder: Base_Type;
Line 99 ⟶ 147:
-- changes the state and outputs the result
 
end LCG;</langsyntaxhighlight>
 
Then we provide a generic implementation:
 
<langsyntaxhighlight Adalang="ada">package body LCG is
 
State: Base_Type := Base_Type'First;
Line 118 ⟶ 166:
end Random;
 
end LCG;</langsyntaxhighlight>
 
Next, we define the MS- and BSD-instantiations of the generic package:
 
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO, LCG;
 
procedure Run_LCGs is
Line 141 ⟶ 189:
Ada.Text_IO.Put_Line(M31'Image(MS_Rand.Random));
end loop;
end Run_LCGs;</langsyntaxhighlight>
 
Finally, we run the program, which generates the following output (note that the first ten lines are from the BSD generator, the next ten from the MS generator):
Line 167 ⟶ 215:
 
=={{header|ALGOL 68}}==
<langsyntaxhighlight lang="algol68">
BEGIN
COMMENT
Line 247 ⟶ 295:
srand (0)
END
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 274 ⟶ 322:
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight AutoHotkeylang="autohotkey">a := 0, b:= [0]
Loop, 10
BSD .= "`t" (a := BSD(a)) "`n"
Line 289 ⟶ 337:
Seed := Mod(214013 * Seed + 2531011, 2147483648)
return, [Seed, Seed // 65536]
}</langsyntaxhighlight>
'''Output:'''
<pre>BSD:
Line 315 ⟶ 363:
30612</pre>
 
=={{header|Batch File}}==
<syntaxhighlight lang="dos">@echo off & setlocal enabledelayedexpansion
<lang batch>
@echo off & setlocal enabledelayedexpansion
 
echo BSD Rand
Line 340 ⟶ 387:
set p2= %2
echo %p1:~-2% %p2:~-10%
goto:eof</syntaxhighlight>
</lang>
'''Output:'''
<pre>
Line 371 ⟶ 416:
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<langsyntaxhighlight lang="bbcbasic"> @% = &D0D
PRINT "MS generator:"
dummy% = FNrandMS(0)
Line 404 ⟶ 449:
DEF FNmuladd(A%,B%,C%) : PRIVATE M% : LOCAL P% : IF M% = 0 DIM P% 8
IF P% THEN [OPT 0 : .M% mul ebx : add eax,ecx : btr eax,31 : ret :]
= USR M%</langsyntaxhighlight>
'''Output:'''
<pre>
Line 438 ⟶ 483:
 
As with dc, bc has no bitwise operators.
<langsyntaxhighlight lang="bc">/* BSD rand */
 
define rand() {
Line 456 ⟶ 501:
 
randseed = 1
rand(); rand(); rand(); print "\n"</langsyntaxhighlight>
 
=={{header|Befunge}}==
This required a bit of trickery to handle signed overflow and negative division in a portable way. It still won't work on all implementations, though. In particular Javascript-based interpreters can't handle the BSD formula because of the way Javascript numbers lose their least significant digits when they become too large.
 
<langsyntaxhighlight lang="befunge">>025*>\::0\`288*::*:****+.55+,"iQ"5982156*:v
v $$_^#!\-1:\%***:*::*882 ++*"yf"3***+***+*<
>025*>\:488**:*/:0\`6"~7"+:*+01-2/-*+."O?+"55v
@ $$_^#!\-1:\%***:*::*882 ++***" ''4C"*+2**,+<</langsyntaxhighlight>
 
{{out}}
Line 491 ⟶ 536:
 
=={{header|Bracmat}}==
<langsyntaxhighlight lang="bracmat">( 2^31:?RANDMAX
& 2^-16:?rshift
& (randBSD=mod$(!seed*1103515245+12345.!RANDMAX):?seed)
Line 506 ⟶ 551:
& 0:?i
& whl'(1+!i:~>10:?i&out$!randMS)
)</langsyntaxhighlight>
 
Output:
Line 535 ⟶ 580:
=={{header|C}}==
In a pretended lib style, this code produces a rand() function depends on compiler macro: <code>gcc -DMS_RAND</code> uses MS style, otherwise it's BSD rand by default.
<langsyntaxhighlight Clang="c">#include <stdio.h>
 
/* always assuming int is at least 32 bits */
Line 575 ⟶ 620:
 
return 0;
}</langsyntaxhighlight>
 
=={{header|C sharp|C#}}==
{{works with|C sharp|C#|6+}}
<!-- By Martin Freedman, 17/01/2018 -->
<syntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
using System.Linq;
using static System.Console;
 
namespace LinearCongruentialGenerator
{
static class LinearCongruentialGenerator
{
static int _seed = (int)DateTime.Now.Ticks; // from bad random gens might as well have bad seed!
static int _bsdCurrent = _seed;
static int _msvcrtCurrent = _seed;
 
static int Next(int seed, int a, int b) => (a * seed + b) & int.MaxValue;
 
static int BsdRand() => _bsdCurrent = Next(_bsdCurrent, 1103515245, 12345);
 
static int MscvrtRand() => _msvcrtCurrent = Next (_msvcrtCurrent << 16,214013,2531011) >> 16;
 
static void PrintRandom(int count, bool isBsd)
{
var name = isBsd ? "BSD" : "MS";
WriteLine($"{name} next {count} Random");
var gen = isBsd ? (Func<int>)(BsdRand) : MscvrtRand;
foreach (var r in Enumerable.Repeat(gen, count))
WriteLine(r.Invoke());
}
 
static void Main(string[] args)
{
PrintRandom(10, true);
PrintRandom(10, false);
Read();
}
}
}</syntaxhighlight>
Produces:
<pre>BSD next 10 Random
1587930915
19022880
1025044953
1143293854
1642451583
1110934092
773706389
1830436778
1527715739
2072016696
MS next 10 Random
24368
8854
28772
16122
11064
24190
23724
6690
14784
21222
</pre>
From a Free Cell Deal solution
<syntaxhighlight lang="csharp">
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace FreeCellDeals
{
public class LCG
{
private int _state;
public bool Microsoft { get; set;}
public bool BSD
{
get
{
return !Microsoft;
}
set
{
Microsoft = !value;
}
}
 
public LCG(bool microsoft = true)
{
_state = (int)DateTime.Now.Ticks;
Microsoft = microsoft;
}
 
public LCG(int n, bool microsoft = true)
{
_state = n;
Microsoft = microsoft;
}
 
public int Next()
{
if (BSD)
{
return _state = (1103515245 * _state + 12345) & int.MaxValue;
}
return ((_state = 214013 * _state + 2531011) & int.MaxValue) >> 16;
}
 
public IEnumerable<int> Seq()
{
while (true)
{
yield return Next();
}
}
}
 
class Program
{
static void Main()
{
LCG ms = new LCG(0, true);
LCG bsd = new LCG(0,false);
Console.WriteLine("Microsoft");
ms.Seq().Take(10).ToList().ForEach(Console.WriteLine);
Console.WriteLine("\nBSD");
bsd.Seq().Take(10).ToList().ForEach(Console.WriteLine);
Console.ReadKey();
}
}
}
</syntaxhighlight>
Output:
<pre>Microsoft
38
7719
21238
2437
8855
11797
8365
32285
10450
30612
 
BSD
12345
1406932606
654583775
1449466924
229283573
1109335178
1051550459
1293799192
794471793
551188310
</pre>
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">#include <iostream>
 
//--------------------------------------------------------------------------------------------------
Line 628 ⟶ 832:
return 0;
}
//--------------------------------------------------------------------------------------------------</langsyntaxhighlight>
Output:
<pre>
Line 660 ⟶ 864:
; C++11
{{works with|C++11}}
<langsyntaxhighlight lang="cpp">#include <iostream>
#include <random>
 
Line 679 ⟶ 883:
return 0;
}</langsyntaxhighlight>
Output:
<pre>
Line 711 ⟶ 915:
=={{header|Clojure}}==
 
<syntaxhighlight lang="clojure">
<lang Clojure>
 
(defn iterator [a b]
Line 723 ⟶ 927:
(take 10 ms) ;-> (38 7719 21238 2437 8855 11797 8365 32285 10450 30612)
 
</syntaxhighlight>
</lang>
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang="lisp">(defun make-rng (&key (seed 0) (mode nil))
"returns an RNG according to :seed and :mode keywords
default mode: bsd
Line 739 ⟶ 943:
 
(let ((rng (make-rng :mode 'ms :seed 1)))
(dotimes (x 10) (format t "MS: ~d~%" (funcall rng))))</langsyntaxhighlight>
 
 
Another solution could be:
<langsyntaxhighlight lang="lisp">(defun linear-random (seed &key (times 1) (bounds (expt 2 31)) (multiplier 1103515245) (adder 12345) (divisor 1) (max 2147483647) (min 0))
(loop for candidate = seed then (mod (+ (* multiplier candidate) adder) bounds)
for result = candidate then (floor (/ candidate divisor))
when (and (< result max) (> result min)) collect result into valid-numbers
when (> (length valid-numbers) times) return result))</langsyntaxhighlight>
 
Which defaults to the BSD formula, but can be customized to any formula with keyword arguments, for example:
<langsyntaxhighlight lang="lisp">(format t "Count:~15tBSD:~30tMS:~%~{~{~a~15t~a~30t~a~%~}~}"
(loop for i from 0 upto 5 collect
(list i
(linear-random 0 :times i)
(linear-random 0 :times i :multiplier 214013 :adder 2531011 :max 32767 :divisor (expt 2 16)))))</langsyntaxhighlight>
 
Outputs:
Line 764 ⟶ 968:
4 229283573 8855
5 1109335178 11797</pre>
 
=={{header|C sharp|C#}}==
<lang Csharp>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace FreeCellDeals
{
public class LCG
{
private int _state;
public bool Microsoft { get; set;}
public bool BSD
{
get
{
return !Microsoft;
}
set
{
Microsoft = !value;
}
}
 
public LCG(bool microsoft = true)
{
_state = (int)DateTime.Now.Ticks;
Microsoft = microsoft;
}
 
public LCG(int n, bool microsoft = true)
{
_state = n;
Microsoft = microsoft;
}
 
public int Next()
{
if (BSD)
{
return _state = (1103515245 * _state + 12345) & int.MaxValue;
}
return ((_state = 214013 * _state + 2531011) & int.MaxValue) >> 16;
}
 
public IEnumerable<int> Seq()
{
while (true)
{
yield return Next();
}
}
}
 
class Program
{
static void Main()
{
LCG ms = new LCG(0, true);
LCG bsd = new LCG(0,false);
Console.WriteLine("Microsoft");
ms.Seq().Take(10).ToList().ForEach(Console.WriteLine);
Console.WriteLine("\nBSD");
bsd.Seq().Take(10).ToList().ForEach(Console.WriteLine);
Console.ReadKey();
}
}
}
</lang>
Output:
<pre>Microsoft
38
7719
21238
2437
8855
11797
8365
32285
10450
30612
 
BSD
12345
1406932606
654583775
1449466924
229283573
1109335178
1051550459
1293799192
794471793
551188310
</pre>
 
=={{header|D}}==
<langsyntaxhighlight lang="d">struct LinearCongruentialGenerator {
enum uint RAND_MAX = (1U << 31) - 1;
uint seed = 0;
Line 889 ⟶ 997:
foreach (immutable i; 0 .. 10)
writeln(rnd.randMS);
}</langsyntaxhighlight>
Output:
<pre>12345
Line 916 ⟶ 1,024:
''dc'' has no bitwise operations, so this program uses the modulus operator (<code>2147483648 %</code>) and division (<code>65536 /</code>). Fortunately, ''dc'' numbers cannot overflow to negative, so the modulus calculation involves only non-negative integers.
 
For BSD rand(): <langsyntaxhighlight lang="dc">[*
* lrx -- (random number from 0 to 2147483647)
*
Line 926 ⟶ 1,034:
[* Set seed to 1, then print the first 3 random numbers. *]sz
1 sR
lrx psz lrx psz lrx psz</langsyntaxhighlight>
 
<pre>1103527590
Line 932 ⟶ 1,040:
662824084</pre>
 
For Microsoft rand(): <langsyntaxhighlight lang="dc">[*
* lrx -- (random number from 0 to 32767)
*
Line 942 ⟶ 1,050:
[* Set seed to 1, then print the first 3 random numbers. *]sz
1 sR
lrx psz lrx psz lrx psz</langsyntaxhighlight>
 
<pre>41
18467
6334</pre>
=={{header|Delphi}}==
{{libheader| System.SysUtils}}
{{libheader| Winapi.Windows}}
{{Trans|C#}}
<syntaxhighlight lang="delphi">
program Linear_congruential_generator;
 
{$APPTYPE CONSOLE}
{$R *.res}
 
uses
System.SysUtils,
Winapi.Windows;
 
type
TRandom = record
private
FSeed: Cardinal;
FBsdCurrent: Cardinal;
FMsvcrtCurrent: Cardinal;
class function Next(seed, a, b: Cardinal): Cardinal; static;
public
constructor Create(const seed: Cardinal);
function Rand(Bsd: Boolean = True): Cardinal;
property Seed: Cardinal read FSeed;
end;
 
{ TRandom }
 
class function TRandom.Next(seed, a, b: Cardinal): Cardinal;
begin
Result := (a * seed + b) and MAXDWORD;
end;
 
function TRandom.Rand(Bsd: Boolean): Cardinal;
begin
if Bsd then
begin
FBsdCurrent := Next(FBsdCurrent, 1103515245, 12345);
Result := FBsdCurrent;
end
else
begin
FMsvcrtCurrent := Next(FMsvcrtCurrent shl 16, 214013, 2531011) shr 16;
Result := FMsvcrtCurrent;
end;
end;
 
constructor TRandom.Create(const seed: Cardinal);
begin
FSeed := seed;
FBsdCurrent := FSeed;
FMsvcrtCurrent := FSeed;
end;
 
var
r: TRandom;
 
procedure PrintRandom(count: Integer; IsBsd: Boolean);
const
NAME: array[Boolean] of string = ('MS', 'BSD');
var
i: Integer;
begin
Writeln(NAME[IsBsd], ' next ', count, ' Random'#10);
for i := 0 to count - 1 do
writeln(' ', r.Rand(IsBsd));
writeln;
end;
 
begin
r.Create(GetTickCount);
PrintRandom(10, True);
PrintRandom(10, False);
readln;
end.
 
</syntaxhighlight>
 
{{out}}
<pre>
BSD next 10 Random
 
3076996592
1668591465
978771438
1655648911
3482994972
245356837
1171712762
1870031019
3901807368
2560221857
 
MS next 10 Random
 
22925
26495
34217
21291
29349
31799
10113
52643
58173
35439
</pre>
=={{header|EasyLang}}==
<syntaxhighlight>
func mul32 a b .
# to avoid overflow with 53bit integer precision with double
ah = a div 0x10000
al = a mod 0x10000
bh = b div 0x10000
bl = b mod 0x10000
return al * bl + al * bh * 0x10000 + bl * ah * 0x10000
.
global state_bsd state_ms .
func rand_bsd .
state_bsd = (mul32 1103515245 state_bsd + 12345) mod 0x80000000
return state_bsd
.
func rand_ms .
state_ms = (214013 * state_ms + 2531011) mod 0x80000000
return state_ms div 0x10000
.
for i = 1 to 5
print rand_bsd
.
print ""
for i = 1 to 5
print rand_ms
.
</syntaxhighlight>
 
{{out}}
<pre>
12345
1406932606
654583775
1449466924
229283573
 
38
7719
21238
2437
8855
</pre>
 
=={{header|EDSAC order code}}==
The first version of this solution had trouble with the "sandwich digit". As pointed out by Wilkes, Wheeler & Gill (1951 edition, page 26), a 35-bit constant cannot be loaded via pseudo-orders if the middle bit (sandwich digit) is 1. One workaround, adopted in the EDSAC solution to the Babbage Problem, is to use the negative of the constant instead. The alternative, which WWG evidently preferred and which is used in the LCG solution posted here, is to load 35-bit constants via the library subroutine R9.
 
The task doesn't specify what random seed is to be used. This program uses 1, with results identical to those from the Elixir program.
<syntaxhighlight lang="edsac">
[Linear congruential generators for pseudo-random numbers.
EDSAC program, Initial Orders 2.]
 
[Library subroutine R9, to read integer constants at load time.
See Wilkes, Wheeler & Gill, 1951 edition, pages 98 & 148.]
..PK
T 56 K [must be loaded at 56]
GKT20FVDL8FA40DUDTFI40FA40FS39FG@S2FG23FA5@T5@E4@
 
[Modification of library subroutine P7.
Prints non-negative integer, up to 10 digits, right-justified.
55 locations, load at even address.
Set up to be called with 'G N', so that caller needn't know its address.
See Wilkes, Wheeler & Gill, 1951 edition, page 18.]
T 46 K [location corresponding to N parameter]
P 72 F [load subroutine at 72]
E 25 K TN
GKA3FT42@A47@T31@ADE10@T31@A48@T31@SDTDH44#@NDYFLDT4DS43@TF
H17@S17@A43@G23@UFS43@T1FV4DAFG50@SFLDUFXFOFFFSFL4FT4DA49@T31@
A1FA43@G20@XFP1024FP610D@524D!FO46@O26@XFO46@SFL8FT4DE39@
 
[BSD linear congruential generator.
Call with 'G B' to initialize, passing seed in 0D.
Call with 'G 1 B' to get next value, returned in 0D.]
T 53 K [location corresponding to B parameter]
P 140 F [load subroutine at 140]
E 25 K TB GK
[0] G 10 @ [jump to initialize]
[1] G 15 @ [jump to get next value]
[2] PF PF [mask, 2^31 - 1]
[4] PF PF [multiplier]
[6] PF PF [added constant]
[Call R9 to set the 3 preceding constants at load time.]
E69KT2#@
2147483647F1103515245F12345#
T8Z
[8] PF PF [current state]
 
[Initialize; caller places seed in 0D]
[10] A 3 F [make jump back to caller]
T 14 @ [plant in code]
A D [load seed passed by caller]
T 8#@ [store as initial state]
[14] Z F [overwritten by jump back to caller]
 
[Get next value from BSD; return it in 0D]
[15] A 3 F [make jump back to caller]
T 28 @ [plant in code, acc := 0]
H 4#@ [mult reg := multiplier]
V 8#@ [acc := state * multiplier]
LF LF L64F [shift 34 left, done as 13 + 13 + 8]
A 6#@ [add the constant]
T D [temp store in 0D]
H 2#@ [mult reg := mask]
C D [acc := result modulo 2^31]
U 8#@ [update state]
T D [also to 0D for caller]
[28] Z F [overwritten by jump back to caller]
 
[Microsoft linear congruential generator.
Call with 'G M' to initialize, passing seed in 0D.
Call with 'G 1 M' to get next value, returned in 0D.
Very similar to code for BSD, so given in condensed form.]
T47KP180FE25KTMGKG10@G15@PFPFPFPFPFPFE69KT2#@
2147483647F214013F2531011# [the 3 constants]
T8ZPFPFA3FT14@ADT8#@ZFA3FT30@H4#@V8#@LFLFL64FA6#@TDH2#@CDU8#@
[Unlike BSD, MS returns the state divided by 2^16]
RF RD [shift 16 right, done as 15 + 1]
T D [to 0D for caller]
[30] Z F [overwritten by jump back to caller]
 
[Main routine]
T 220 K [load at 220]
G K [set theta parameter as usual]
[0] PF PF [35-bit seed]
[Use library subroutine R9 to set seed]
E69K T#@
1# [non-negative seed followed by '#']
T2Z
[2] P F [negative counter for loop]
[3] P 10 F [to print first 10 values]
[Characters for printing]
[4] B F
[5] D F
[6] E F
[7] M F
[8] S F
[9] C F [colon when in figures mode]
[10] K 2048 F [set letters on teleprinter]
[11] # F [set figures on teleprinter]
[12] @ F [carriage return]
[13] & F [line feed]
[14] K 4096 F [null]
 
[Enter with acc = 0]
[Print 'SEED:' and then the seed]
[15] O10@ O8@ O6@ O6@ O5@ O11@ O9@
A #@ [load seed]
T D [store in 0D for printing]
[24] A 24 @ [pass return address]
G N [call print subroutine]
O12@ O13@ [print new line]
 
[Initialize the BSD generator]
A #@ [load seed]
T D [pass seed in 0D]
[30] A 30 @ [pass return address]
G B [call BSD initializer]
O10@ O4@ O8@ O5@ O11@ O9@ O12@ O13@ [print 'BSD:']
S 3 @ [load negative of count]
[Loop printing values from BSD generator]
[41] T 2 @ [update negative counter]
[42] A 42 @ [pass return address]
G 1 B [call BSD to get next value in 0D]
[44] A 44 @ [pass return address]
G N [call print subroutine]
O12@ O13@ [print new line]
A 2 @ [load negative counter]
A 2 F [increment]
G 41 @ [loop until counter = 0]
 
[Microsoft LCG, very similar to BSD, so given in condensed form]
A#@TDA53@GMO10@O7@O8@O11@O9@O12@O13@S3@T2@A64@G1MA66@GNO12@O13@A2@A2FG63@
 
O 14 @ [print null to flush teleprinter buffer]
Z F [stop]
E 15 Z [define entry point]
P F [acc = 0 on entry]
</syntaxhighlight>
{{out}}
<pre>
SEED: 1
BSD:
1103527590
377401575
662824084
1147902781
2035015474
368800899
1508029952
486256185
1062517886
267834847
MS:
41
18467
6334
26500
19169
15724
11478
29358
26962
24464
</pre>
 
=={{header|Elixir}}==
<langsyntaxhighlight lang="elixir">defmodule LCG do
def ms_seed(seed) do
Process.put(:ms_state, seed)
Line 983 ⟶ 1,401:
:io.format "~11w~8w~n", [LCG.bsd_rand, LCG.ms_rand]
end)
end)</langsyntaxhighlight>
 
{{out}}
Line 1,016 ⟶ 1,434:
=={{header|Erlang}}==
{{trans|Elixir}}
<langsyntaxhighlight lang="erlang">-module(lcg).
-export([bsd_seed/1, ms_seed/1, bsd_rand/0, ms_rand/0]).
 
Line 1,036 ⟶ 1,454:
ms_seed(0),
io:fwrite("~10s~c~5s~n", ["BSD", 9, "MS"]),
lists:map(fun(_) -> io:fwrite("~10w~c~5w~n", [bsd_rand(),9,ms_rand()]) end, lists:seq(1,10)).</langsyntaxhighlight>
 
{{Out}}
Line 1,053 ⟶ 1,471:
=={{header|ERRE}}==
ERRE doesn't generate the proper output from the BSD constants; it uses double-precision floating point, which is not enough for some of the intermediate products: for exact computation you can use MULPREC program. The BSD series deviates starting with the third value (see sample output below).
<langsyntaxhighlight ERRElang="erre">PROGRAM RNG
 
!$DOUBLE
Line 1,086 ⟶ 1,504:
PRINT(TAB(10);XRND)
END FOR
END PROGRAM</langsyntaxhighlight>
{{out}}
<pre>
Line 1,115 ⟶ 1,533:
=={{header|F_Sharp|F#}}==
 
<langsyntaxhighlight lang="fsharp">module lcg =
let bsd seed =
let state = ref seed
Line 1,127 ⟶ 1,545:
state := (214013 * !state + 2531011) &&& System.Int32.MaxValue
!state / (1<<<16))
</syntaxhighlight>
</lang>
<pre>let rndBSD = lcg.bsd 0;;
let BSD=[for n in [0 .. 9] -> rndBSD()];;
Line 1,139 ⟶ 1,557:
val MS : int list =
[38; 7719; 21238; 2437; 8855; 11797; 8365; 32285; 10450; 30612]</pre>
 
=={{header|Factor}}==
{{works with|Factor|0.98}}
<syntaxhighlight lang="factor">USING: fry io kernel lists lists.lazy math prettyprint ;
 
: lcg ( seed a c m quot: ( state -- rand ) -- list )
[ '[ _ * _ + _ mod ] lfrom-by ] [ lmap-lazy cdr ] bi* ; inline
 
0 1103515245 12345 2147483648 [ ] lcg ! bsd
0 214013 2531011 2147483648 [ -16 shift ] lcg ! ms
[ 10 swap ltake [ . ] leach nl ] bi@</syntaxhighlight>
{{out}}
<pre>
12345
1406932606
654583775
1449466924
229283573
1109335178
1051550459
1293799192
794471793
551188310
 
38
7719
21238
2437
8855
11797
8365
32285
10450
30612
</pre>
 
=={{header|Forth}}==
<langsyntaxhighlight lang="forth">1 31 lshift 1- constant MAX-RAND-BSD
1 15 lshift 1- constant MAX-RAND-MS
 
Line 1,157 ⟶ 1,610:
;
 
test-random</langsyntaxhighlight>
 
Output:
Line 1,176 ⟶ 1,629:
=={{header|Fortran}}==
{{works with|Fortran|90 and later}}
<langsyntaxhighlight lang="fortran">module lcgs
implicit none
 
Line 1,217 ⟶ 1,670:
write(*, "(2i12)") bsdrand(), msrand()
end do
end program</langsyntaxhighlight>
Output
<pre> BSD MS
Line 1,230 ⟶ 1,683:
794471793 10450
551188310 30612</pre>
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">' version 04-11-2016
' compile with: fbc -s console
 
Line 1,287 ⟶ 1,741:
Print : Print "hit any key to end program"
Sleep
End</langsyntaxhighlight>
{{out}}
<pre>MS generator
Line 1,312 ⟶ 1,766:
794471793
551188310</pre>
 
=={{header|Fōrmulæ}}==
 
{{FormulaeEntry|page=https://formulae.org/?script=examples/Linear_congruential_generator}}
 
'''Solution'''
 
'''Definitions'''
 
[[File:Fōrmulæ - Linear congruential generator 01.png]]
 
[[File:Fōrmulæ - Linear congruential generator 02.png]]
 
'''Test case'''
 
[[File:Fōrmulæ - Linear congruential generator 03.png]]
 
[[File:Fōrmulæ - Linear congruential generator 04.png]]
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 1,348 ⟶ 1,820:
example(0)
example(1)
}</langsyntaxhighlight>
Output:
<pre>
Line 1,369 ⟶ 1,841:
 
=={{header|Haskell}}==
<langsyntaxhighlight lang="haskell">bsd = tail . iterate (\n -> (n * 1103515245 + 12345) `mod` 2^31)
msr = map (`div` 2^16) . tail . iterate (\n -> (214013 * n + 2531011) `mod` 2^31)
 
main = do
print $ take 10 $ bsd 0 -- can take seeds other than 0, of course
print $ take 10 $ msr 0</langsyntaxhighlight>
 
=={{header|Icon}} and {{header|Unicon}}==
The following LCRNG's behave in the same way maintaining the state (seed) from round to round. There is an srand procedure for each lcrng that maintains the seed state and allows the user to assign a new state.
<langsyntaxhighlight Iconlang="icon">link printf
 
procedure main()
Line 1,402 ⟶ 1,874:
procedure rand_MS() #: lcrng
return ishift(srand_MS((214013 * srand_MS() + 2531011) % 2147483648),-16)
end</langsyntaxhighlight>
 
{{libheader|Icon Programming Library}}
Line 1,409 ⟶ 1,881:
=={{header|J}}==
'''Solution:'''
<langsyntaxhighlight lang="j">lcg=: adverb define
0 m lcg y NB. default seed of 0
:
Line 1,417 ⟶ 1,889:
 
rand_bsd=: (1103515245 12345 , <.2^31) lcg
rand_ms=: (2^16) <.@:%~ (214013 2531011 , <.2^31) lcg</langsyntaxhighlight>
'''Example Use:'''
<langsyntaxhighlight lang="j"> rand_bsd 10
12345 1406932606 654583775 1449466924 229283573 1109335178 1051550459 1293799192 794471793 551188310
654583775 rand_bsd 4
Line 1,426 ⟶ 1,898:
38 7719 21238 2437 8855 11797 8365 32285 10450 30612
1 rand_ms 5 NB. seed of 1
41 18467 6334 26500 19169</langsyntaxhighlight>
 
=={{header|Java}}==
{{works with|Java|8}}
<langsyntaxhighlight lang="java">import java.util.stream.IntStream;
import static java.util.stream.IntStream.iterate;
 
Line 1,452 ⟶ 1,924:
.map(i -> i >> 16);
}
}</langsyntaxhighlight>
 
<pre>BSD:
Line 1,479 ⟶ 1,951:
 
=={{header|jq}}==
The Go implementation of jq (gojq) supports unlimited-precision integer arithmetic and therefore linear congruential generators (LCGs) can be trivially written for gojq.
Currently, jq arithmetic is based on IEEE 754 64-bit numbers. As a result, it is trivial to implement the Microsoft linear congruential generator (LCG), but the BSD generator requires some kind of "big integer" support. In this section, therefore, we first present functions to support the Microsoft LCG, and then present functions to support the LCG on the assumption that a suitable jq "BigInt" library is available.
 
The C implementation of jq, however, currently uses IEEE 754 64-bit numbers for arithmetic, so a BSD generator for the C implementation of jq would require some kind of "big integer" support.
 
In this entry, therefore, we first present functions for the Microsoft LCG that can be used with jq or gojq, and then present functions to support the BSD generator on the assumption that a suitable "BigInt" library is available.
====Microsoft LCG====
<langsyntaxhighlight lang="jq"># 15-bit integers generated using the same formula as rand()
# from the Microsoft C Runtime.
# Input: [ count, state, rand ]
Line 1,494 ⟶ 1,970:
| next_rand_Microsoft # the seed is not so random
| recurse(if .[0] < n then next_rand_Microsoft else empty end)
| .[2];</langsyntaxhighlight>
'''Example''':
rand_Microsoft(1;5)
{{out}}
<langsyntaxhighlight lang="sh">41
18467
6334
26500
19169</langsyntaxhighlight>
====BSD LCG====
The following code has been tested with the "BigInt" library at [https://gist.github.com/pkoppstein/d06a123f30c033195841].
<langsyntaxhighlight lang="jq"># BSD rand()
# Input: [count, previous]
def next_rand_berkeley:
Line 1,518 ⟶ 1,994:
| next_rand_berkeley # skip the seed itself
| recurse(if .[0] < n then next_rand_berkeley else empty end)
| .[1];</langsyntaxhighlight>
'''Example''':
rand_berkeley(1;5)
{{out}}
<langsyntaxhighlight lang="sh">1103527590
377401575
662824084
1147902781
2035015474</langsyntaxhighlight>
 
=={{header|Julia}}==
{{works with|Julia|0.6}}
 
<tt>getlgc</tt> creates a linear congruential generator as a closure. This function is used to create the two generators called for by the task.
<syntaxhighlight lang="julia">using Printf
<lang julia>function getlgc(r::Integer, a::Integer, c::Integer, m::Integer, sh::Integer)
 
function getlgc(r::Integer, a::Integer, c::Integer, m::Integer, sh::Integer)
state = r
return function lgcrand()
Line 1,553 ⟶ 2,029:
for _ in 1:nrep
@printf("%14d\n", msrand())
end</langsyntaxhighlight>
 
{{out}}
Line 1,581 ⟶ 2,057:
 
=={{header|K}}==
<langsyntaxhighlight Klang="k"> bsd:{1_ y{((1103515245*x)+12345)!(_2^31)}\x}
ms:{1_(y{_(((214013*x)+2531011)!(_2^31))}\x)%(_2^16)}
 
Line 1,587 ⟶ 2,063:
12345 1406932606 654583775 1449466924 229283573 1109335178 1051550459 1293799192 794471793 551188310
ms[0;10]
38 7719 21238 2437 8855 11797 8365 32285 10450 30612</langsyntaxhighlight>
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.1.3
 
class Lcg(val a: Long, val c: Long, val m: Long, val d: Long, val s: Long) {
Line 1,608 ⟶ 2,084:
val msc = Lcg(214013, 2531011, 1 shl 31, 1 shl 16, 0)
for (i in 1..10) println("${msc.nextInt()}")
}</langsyntaxhighlight>
 
{{out}}
Line 1,638 ⟶ 2,114:
 
=={{header|Liberty BASIC}}==
<syntaxhighlight lang="lb">
<lang lb>
'by default these are 0
global BSDState
Line 1,662 ⟶ 2,138:
randMS = int(MSState / 2 ^ 16)
end function
</syntaxhighlight>
</lang>
 
=={{header|Logo}}==
Line 1,668 ⟶ 2,144:
Note that, perhaps ironically, [[UCB Logo]], as of version 6.0, doesn't generate the proper output from the BSD constants; it uses double-precision floating point, which is not enough for some of the intermediate products. In UCBLogo, the BSD series deviates starting with the third value (see sample output below).
 
<langsyntaxhighlight Logolang="logo">; Configuration parameters for Microsoft and BSD implementations
make "LCG_MS [214013 2531011 65536 2147483648]
make "LCG_BSD [1103515245 12345 1 2147483648]
Line 1,697 ⟶ 2,173:
print []
]
bye</langsyntaxhighlight>
 
Output:<pre>12345
Line 1,738 ⟶ 2,214:
This requires Lua 5.3 or later because previous versions didn't have support for large integers or integral arithmetic operations.
 
<langsyntaxhighlight lang="lua">local RNG = {
new = function(class, a, c, m, rand)
local self = setmetatable({}, class)
Line 1,764 ⟶ 2,240:
print(("\t%10d"):format(ms.rnd()))
end
</syntaxhighlight>
</lang>
 
{{Out}}
Line 1,791 ⟶ 2,267:
</pre>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">BSDrand[x_] := Mod[x*1103515245 + 12345, 2147483648]
NestList[BSDrand, 0, 10]
-> {0, 12345, 1406932606, 654583775, 1449466924, 229283573, 1109335178, 1051550459, 1293799192, 794471793, 551188310}
Line 1,798 ⟶ 2,274:
MSrand[x_] := Mod[x*214013 + 2531011, 2147483648]
BitShiftRight[ NestList[MSrand, 0, 10], 16]
-> {0, 38, 7719, 21238, 2437, 8855, 11797, 8365, 32285, 10450, 30612}</langsyntaxhighlight>
 
=={{header|Maxima}}==
<langsyntaxhighlight lang="maxima">seed: 0$
ms_rand() := quotient(seed: mod(214013 * seed + 2531011, 2147483648), 65536)$
makelist(ms_rand(), 20); /* see http://oeis.org/A096558 */
Line 1,814 ⟶ 2,290:
[12345, 1406932606, 654583775, 1449466924, 229283573, 1109335178, 1051550459,
1293799192, 794471793, 551188310, 803550167, 1772930244, 370913197, 639546082, 1381971571,
1695770928, 2121308585, 1719212846, 996984527, 1157490780]</langsyntaxhighlight>
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">proc bsdRand(seed: int): iterator: int =
var seedstate = seed
result = iterator: int =
while true:
seedstate = (11035152451_103_515_245 * seedstate + 1234512_345) and 0x7fffffff
yield seedstate
 
proc msvcrtRand(seed: int): iterator: int =
var seedstate = seed
result = iterator: int =
while true:
seedstate = (214013214_013 * seedstate + 25310112_531_011) and 0x7fffffff
yield seed</lang>state shr 16
 
echo "BSD with seed = 1 (OEIS A096553):"
var count = 0
let iter1 = bsdRand(1)
for val in iter1():
echo val
inc count
if count == 10:
break
 
echo ""
echo "Microsoft with seed = 0 (OEIS A096558):"
count = 0
let iter2 = msvcrtRand(0)
for val in iter2():
echo val
inc count
if count == 10:
break</syntaxhighlight>
 
{{out}}
<pre>BSD with seed = 1 (OEIS A096553):
1103527590
377401575
662824084
1147902781
2035015474
368800899
1508029952
486256185
1062517886
267834847
 
Microsoft with seed = 0 (OEIS A096558):
38
7719
21238
2437
8855
11797
8365
32285
10450
30612</pre>
 
=={{header|OCaml}}==
<syntaxhighlight lang="ocaml">let lcg31 a c x =
(a * x + c) land 0x7fffffff
 
let rng_seq rng seed =
Seq.iterate rng (rng seed)
 
let lcg_bsd =
rng_seq (lcg31 1103515245 12345)
 
let lcg_ms seed =
Seq.map (fun r -> r lsr 16) (rng_seq (lcg31 214013 2531011) seed)
 
(* test code *)
let () =
let print_first8 sq =
sq |> Seq.take 8 |> Seq.map string_of_int
|> List.of_seq |> String.concat " " |> print_endline
in
List.iter print_first8 [lcg_bsd 0; lcg_bsd 1; lcg_ms 0; lcg_ms 1]</syntaxhighlight>
{{out}}
<pre>
12345 1406932606 654583775 1449466924 229283573 1109335178 1051550459 1293799192
1103527590 377401575 662824084 1147902781 2035015474 368800899 1508029952 486256185
38 7719 21238 2437 8855 11797 8365 32285
41 18467 6334 26500 19169 15724 11478 29358
</pre>
 
=={{header|Oforth}}==
Line 1,835 ⟶ 2,383:
Function genLCG returns a block object that, when performed, will return the next random number from the LCG.
 
<langsyntaxhighlight Oforthlang="oforth">: genLCG(a, c, m, seed)
| ch |
Channel newSize(1) dup send(seed) drop ->ch
#[ ch receive a * c + m mod dup ch send drop ] ;</langsyntaxhighlight>
 
{{out}}
Line 1,869 ⟶ 2,417:
=={{header|PARI/GP}}==
Note that up to PARI/GP version 2.4.0, <code>random()</code> used a linear congruential generator.
<langsyntaxhighlight lang="parigp">BSDseed=Mod(1,1<<31);
MSFTseed=Mod(1,1<<31);
BSD()=BSDseed=1103515245*BSDseed+12345;lift(BSDseed);
MSFT()=MSFTseed=214013*MSFTseed+2531011;lift(MSFTseed)%(1<<31);</langsyntaxhighlight>
 
=={{header|Pascal}}==
<syntaxhighlight lang="pascal">Program LinearCongruentialGenerator(output);
{{incorrect|Pascal|Incorrect output. [[User:Petelomax|Pete Lomax]] ([[User talk:Petelomax|talk]])}}
{$mode iso}
<lang pascal>Program LinearCongruentialGenerator(output);
 
var
x1, x2: int64;
 
function bsdrand: longintcardinal;
const
a = 1103515245;
Line 1,890 ⟶ 2,437:
bsdrand := x1;
end;
 
function msrand: longintcardinal;
const
a = 214013;
Line 1,900 ⟶ 2,447:
msrand := x2 div 65536;
end;
 
var
i: longintcardinal;
begin
writeln(' BSD MS');
Line 1,909 ⟶ 2,456:
for i := 1 to 10 do
writeln(bsdrand:12, msrand:12);
end.</lang>
</syntaxhighlight>
Output:
<pre> BSD MS
12345 7584 38
11246521451406932606 32777719
1499545833 654583775 306721238
15584060491449466924 31446 2437
696007321229283573 13069 8855
1109335178 56579025 1734311797
13127058651051550459 25108365
1293799192 811881729 526432285
1301653753 794471793 21298 10450
1318262577 551188310 27689 30612</pre>
 
=={{header|Perl}}==
Creates a magic scalar whose value is next in the LCG sequence when read.<langsyntaxhighlight lang="perl">use strict;
package LCG;
 
Line 1,963 ⟶ 2,511:
 
print "\nMS:\n";
print "$rand\n" for 1 .. 10;</langsyntaxhighlight>output<syntaxhighlight lang="text">BSD:
12345
1406932606
Line 1,985 ⟶ 2,533:
32285
10450
30612</langsyntaxhighlight>
 
=={{header|Perl 6}}==
 
We'll define subroutines implementing the LCG algorithm for each version. We'll make them return a lazy list.
 
<lang perl6>constant modulus = 2**31;
sub bsd {
$^seed, ( 1103515245 * * + 12345 ) % modulus ... *
}
sub ms {
map * +> 16, (
$^seed, ( 214013 * * + 2531011 ) % modulus ... *
)
}
say 'BSD LCG first 10 values (first one is the seed):';
.say for bsd(0)[^10];
say "\nMS LCG first 10 values (first one is the seed):";
.say for ms(0)[^10];</lang>
 
<pre>BSD LCG first 10 values (first one is the seed):
0
12345
1406932606
654583775
1449466924
229283573
1109335178
1051550459
1293799192
794471793
 
MS LCG first 10 values (first one is the seed):
0
38
7719
21238
2437
8855
11797
8365
32285
10450</pre>
 
=={{header|Phix}}==
{{libheader|Phix/mpfr}}
As per the comments, I had to resort to bigatom to get BSDrnd() to work on 32-bit.
As per the comments, I had to resort to gmp to get BSDrnd() to work on 32-bit.
<lang Phix>atom seed
<!--<syntaxhighlight lang="phix">(phixonline)-->
 
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
include builtins/bigatom.e
<span style="color: #004080;">atom</span> <span style="color: #000000;">seed</span>
bigatom ba_seed
 
<span style="color: #008080;">include</span> <span style="color: #000000;">builtins</span><span style="color: #0000FF;">/</span><span style="color: #004080;">mpfr</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span>
function BSDrnd()
ba_seed = ba_remainder(ba_add(ba_multiply(1103515245,ba_seed),12345), #8000_0000)
<span style="color: #008080;">function</span> <span style="color: #000000;">BSDrnd</span><span style="color: #0000FF;">()</span>
return ba_seed
<span style="color: #000080;font-style:italic;">-- oh dear, native only works on 64-bit,
end function
-- as per ERRE and UCBLogo above on 32-bit...
 
-- seed = remainder(1103515245 * seed + 12345, #8000_0000)
--function BSDrnd() -- (only works on 64-bit, as per ERRE and UCBLogo above on 32-bit)
-- so, resort to gmp, with the added twist than both
-- seed = remainder(1103515245 * seed + 12345, #8000_0000)
-- 1103515245 and #8000_0000 are greater than 1GB and
-- return seed
-- therefore a smidge too big & need some extra help...</span>
--end function
<span style="color: #004080;">mpz</span> <span style="color: #000000;">z</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">mpz_init</span><span style="color: #0000FF;">(</span><span style="color: #000000;">seed</span><span style="color: #0000FF;">),</span>
 
<span style="color: #000000;">m9</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">mpz_init</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"1103515245"</span><span style="color: #0000FF;">),</span>
function MSrnd()
<span style="color: #000000;">h8</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">mpz_init</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"0x80000000"</span><span style="color: #0000FF;">)</span>
seed = and_bits(seed*214013+2531011,#7FFFFFFF)
<span style="color: #7060A8;">mpz_mul</span><span style="color: #0000FF;">(</span><span style="color: #000000;">z</span><span style="color: #0000FF;">,</span><span style="color: #000000;">z</span><span style="color: #0000FF;">,</span><span style="color: #000000;">m9</span><span style="color: #0000FF;">)</span>
return floor(seed/power(2,16))
<span style="color: #7060A8;">mpz_add_si</span><span style="color: #0000FF;">(</span><span style="color: #000000;">z</span><span style="color: #0000FF;">,</span><span style="color: #000000;">z</span><span style="color: #0000FF;">,</span><span style="color: #000000;">12345</span><span style="color: #0000FF;">)</span>
end function
<span style="color: #7060A8;">mpz_fdiv_r</span><span style="color: #0000FF;">(</span><span style="color: #000000;">z</span><span style="color: #0000FF;">,</span><span style="color: #000000;">z</span><span style="color: #0000FF;">,</span><span style="color: #000000;">h8</span><span style="color: #0000FF;">)</span>
 
<span style="color: #000000;">seed</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">mpz_get_atom</span><span style="color: #0000FF;">(</span><span style="color: #000000;">z</span><span style="color: #0000FF;">)</span>
--seed = 0
<span style="color: #008080;">return</span> <span style="color: #000000;">seed</span>
ba_seed = ba_new(0)
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
?"BSDrnd"
--for i=1 to 10 do ?BSDrnd() end for -- (64-bit only)
<span style="color: #008080;">function</span> <span style="color: #000000;">MSrnd</span><span style="color: #0000FF;">()</span>
for i=1 to 10 do puts(1,ba_sprintf("%B\n",BSDrnd())) end for
<span style="color: #000000;">seed</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">and_bits</span><span style="color: #0000FF;">(</span><span style="color: #000000;">seed</span><span style="color: #0000FF;">*</span><span style="color: #000000;">214013</span><span style="color: #0000FF;">+</span><span style="color: #000000;">2531011</span><span style="color: #0000FF;">,</span><span style="color: #000000;">#7FFFFFFF</span><span style="color: #0000FF;">)</span>
seed = 0
<span style="color: #008080;">return</span> <span style="color: #7060A8;">floor</span><span style="color: #0000FF;">(</span><span style="color: #000000;">seed</span><span style="color: #0000FF;">/</span><span style="color: #7060A8;">power</span><span style="color: #0000FF;">(</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,</span><span style="color: #000000;">16</span><span style="color: #0000FF;">))</span>
?"MSrnd"
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
for i=1 to 10 do ?MSrnd() end for</lang>
<span style="color: #000000;">seed</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
<span style="color: #0000FF;">?</span><span style="color: #008000;">"BSDrnd"</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">10</span> <span style="color: #008080;">do</span> <span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%d\n"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">BSDrnd</span><span style="color: #0000FF;">())</span> <span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #000000;">seed</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
<span style="color: #0000FF;">?</span><span style="color: #008000;">"MSrnd"</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">10</span> <span style="color: #008080;">do</span> <span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%d\n"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">MSrnd</span><span style="color: #0000FF;">())</span> <span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>
Line 2,089 ⟶ 2,601:
=={{header|PHP}}==
{{works with|PHP|5.3+}}
<langsyntaxhighlight lang="php"><?php
function bsd_rand($seed) {
return function() use (&$seed) {
Line 2,113 ⟶ 2,625:
echo $lcg(), " ";
echo "\n";
?></langsyntaxhighlight>
 
=={{header|Picat}}==
===Methods as hard coded predicates===
<syntaxhighlight lang="picat">go =>
 
% BSD
println(bsd=[bsd() : _ in 1..10]),
bsd_seed(1),
println(bsd2=[bsd() : _ in 1..10]),
 
% MS
println(ms=[ms() : _ in 1..10]),
ms_seed(1),
println(ms2=[ms() : _ in 1..10]),
 
nl.
 
% BSD
bsd_seed(Seed) =>
get_global_map().put(bsd_state, Seed).
bsd = Rand =>
M = get_global_map(),
Seed = cond(M.has_key(bsd_state), M.get(bsd_state),0),
Rand = (1103515245*Seed + 12345) mod 2**31,
M.put(bsd_state,Rand).
% Microsoft
ms_seed(Seed) =>
get_global_map().put(ms_state, Seed).
ms = Rand div 2**16 =>
M = get_global_map(),
Seed = cond(M.has_key(ms_state),M.get(ms_state),0),
Rand = ((214013*Seed + 2531011) mod 2**31),
M.put(ms_state,Rand).</syntaxhighlight>
 
{{out}}
<pre>bsd = [12345,1406932606,654583775,1449466924,229283573,1109335178,1051550459,1293799192,794471793,551188310]
bsd2 = [1103527590,377401575,662824084,1147902781,2035015474,368800899,1508029952,486256185,1062517886,267834847]
ms = [38,7719,21238,2437,8855,11797,8365,32285,10450,30612]
ms2 = [41,18467,6334,26500,19169,15724,11478,29358,26962,24464]</pre>
 
===Generalized version===
Using a global global map for setting/setting seeds etc.
<syntaxhighlight lang="picat">go2 =>
 
% BSD
lcg_init(bsd,1103515245,12345,2**31,1),
println([lcg(bsd) : _ in 1..10]),
 
lcg_init(bsd,1,1103515245,12345,2**31,1),
println([lcg(bsd) : _ in 1..10]),
 
% MS
lcg_init(ms,214013,2531011,2**31,2**16),
println([lcg(ms) : _ in 1..10]),
 
lcg_init(ms,1,214013,2531011,2**31,2**16),
println([lcg(ms) : _ in 1..10]),
 
% unknown (-> error)
println([lcg(unknown) : _ in 1..10]),
 
nl.
 
% default seed is 0
lcg_init(Type,Multiplier,Adder,Mod,OutputDivisor) =>
lcg_init(Type,0,Multiplier,Adder,Mod,OutputDivisor).
 
lcg_init(Type,Seed,Multiplier,Adder,Mod,OutputDivisor) =>
get_global_map().put(Type,
new_map([seed=Seed,multiplier=Multiplier,adder=Adder,mod=Mod,outputDivisor=OutputDivisor])).
 
lcg(Type) = Rand div M.get(outputDivisor) =>
if not get_global_map().has_key(Type) then
throw $lcg(Type,unknown_LCG_type)
end,
M = get_global_map().get(Type),
Rand = ((M.get(multiplier)*M.get(seed) + M.get(adder)) mod M.get(mod)),
M.put(seed,Rand),
get_global_map().put(Type,M).</syntaxhighlight>
 
{{out}}
<pre>[12345,1406932606,654583775,1449466924,229283573,1109335178,1051550459,1293799192,794471793,551188310]
[1103527590,377401575,662824084,1147902781,2035015474,368800899,1508029952,486256185,1062517886,267834847]
[38,7719,21238,2437,8855,11797,8365,32285,10450,30612]
[41,18467,6334,26500,19169,15724,11478,29358,26962,24464]
*** lcg(unknown,unknown_LCG_type)</pre>
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(zero *BsdSeed *MsSeed)
 
(de bsdRand ()
Line 2,125 ⟶ 2,724:
(>> 16
(setq *MsSeed
(& (+ 2531011 (* 214013 *MsSeed)) `(dec (** 2 31))) ) ) )</langsyntaxhighlight>
Output:
<pre>: (do 7 (printsp (bsdRand)))
Line 2,134 ⟶ 2,733:
 
=={{header|PL/I}}==
<syntaxhighlight lang="text">
(nofixedoverflow, nosize):
LCG: procedure options (main);
Line 2,163 ⟶ 2,762:
 
end LCG;
</syntaxhighlight>
</lang>
OUTPUT:
<pre>
Line 2,190 ⟶ 2,789:
 
=={{header|PowerShell}}==
<langsyntaxhighlight lang="powershell">
Function msstate{
Param($current_seed)
Line 2,215 ⟶ 2,814:
$seed = randBSD($seed)
Write-Host $seed}
</syntaxhighlight>
</lang>
 
{{Out}}
Line 2,234 ⟶ 2,833:
 
=={{header|PureBasic}}==
<langsyntaxhighlight lang="purebasic">Procedure ms_LCG(seed.q = -1)
Static state.q
If seed >= 0
Line 2,270 ⟶ 2,869:
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
CloseConsole()
EndIf</langsyntaxhighlight>
Sample output:
<pre>BSD (seed = 1)
Line 2,287 ⟶ 2,886:
 
=={{header|Python}}==
<langsyntaxhighlight lang="python">def bsd_rand(seed):
def rand():
rand.seed = (1103515245*rand.seed + 12345) & 0x7fffffff
Line 2,299 ⟶ 2,898:
return rand.seed >> 16
rand.seed = seed
return rand</langsyntaxhighlight>
{{works with|Python|3.x}}
<langsyntaxhighlight lang="python">def bsd_rand(seed):
def rand():
nonlocal seed
Line 2,313 ⟶ 2,912:
seed = (214013*seed + 2531011) & 0x7fffffff
return seed >> 16
return rand</langsyntaxhighlight>
 
=={{header|Quackery}}==
 
<syntaxhighlight lang="quackery"> [ number$
10 over size -
space swap of
swap join echo$ ] is echonum ( n --> )
 
[ stack 0 ] is BSD-seed ( --> n )
 
[ BSD-seed take
1103515245 *
12345 +
hex 7FFFFFFF &
dup BSD-seed put ] is BSD-rand ( --> n )
 
[ stack 0 ] is MCR-seed ( --> n )
 
[ MCR-seed take
214013 *
2531011 +
hex 7FFFFFFF &
dup MCR-seed put
16 >> ] is MCR-rand ( --> n )
 
say " BSD-rand MCR-rand" cr
10 times
[ BSD-rand echonum
MCR-rand echonum cr ]</syntaxhighlight>
 
{{out}}
 
<pre> BSD-rand MCR-rand
12345 38
1406932606 7719
654583775 21238
1449466924 2437
229283573 8855
1109335178 11797
1051550459 8365
1293799192 32285
794471793 10450
551188310 30612
</pre>
 
=={{header|R}}==
<syntaxhighlight lang="r">library(gmp) # for big integers
 
rand_BSD <- function(n = 1) {
a <- as.bigz(1103515245)
c <- as.bigz(12345)
m <- as.bigz(2^31)
x <- rep(as.bigz(0), n)
x[1] <- (a * as.bigz(seed) + c) %% m
i <- 1
while (i < n) {
x[i+1] <- (a * x[i] + c) %% m
i <- i + 1
}
as.integer(x)
}
 
seed <- 0
rand_BSD(10)
## [1] 12345 1406932606 654583775 1449466924 229283573 1109335178
## [7] 1051550459 1293799192 794471793 551188310
 
rand_MS <- function(n = 1) {
a <- as.bigz(214013)
c <- as.bigz(2531011)
m <- as.bigz(2^31)
x <- rep(as.bigz(0), n)
x[1] <- (a * as.bigz(seed) + c) %% m
i <- 1
while (i < n) {
x[i+1] <- (a * x[i] + c) %% m
i <- i + 1
}
as.integer(x / 2^16)
}
 
seed <- 0
rand_MS(10)
## [1] 38 7719 21238 2437 8855 11797 8365 32285 10450 30612</syntaxhighlight>
 
=={{header|Racket}}==
Line 2,319 ⟶ 3,002:
The following solution uses generators and transcribes the mathematical formulas above directly. It does not attempt to be efficient.
 
<langsyntaxhighlight lang="racket">
#lang racket
(require racket/generator)
Line 2,340 ⟶ 3,023:
(define bsd-rand (rand bsd-update identity))
(define ms-rand (rand ms-update (λ (x) (quotient x (expt 2 16)))))
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
(formerly Perl 6)
 
We'll define subroutines implementing the LCG algorithm for each version. We'll make them return a lazy list.
 
<syntaxhighlight lang="raku" line>constant modulus = 2**31;
sub bsd {
$^seed, ( 1103515245 * * + 12345 ) % modulus ... *
}
sub ms {
map * +> 16, (
$^seed, ( 214013 * * + 2531011 ) % modulus ... *
)
}
say 'BSD LCG first 10 values (first one is the seed):';
.say for bsd(0)[^10];
say "\nMS LCG first 10 values (first one is the seed):";
.say for ms(0)[^10];</syntaxhighlight>
 
<pre>BSD LCG first 10 values (first one is the seed):
0
12345
1406932606
654583775
1449466924
229283573
1109335178
1051550459
1293799192
794471793
 
MS LCG first 10 values (first one is the seed):
0
38
7719
21238
2437
8855
11797
8365
32285
10450</pre>
 
=={{header|REXX}}==
<langsyntaxhighlight lang="rexx">/*REXX program isuses a linear congruential generator which(LCG) that simulates the old BSD and MS random */
/*──────────────────── and MS random number generators.: BSD= 0 ──► 0──►(2**^31)-1 MS= 0 ──► 0──►(2**^16)-1 */
numeric digits 20 /*useduse enough digitsdec. digs for the multiply.*/
two@@16= 2**16 /*use a variable to contain 2^16 */
two@@31= 2**31 /* " " " " " 2^32 */
 
do seed=0 to 1 do seed=0 for 2; bsd= seed /*perform for seed=0 and also seed=1.*/
bsd=seed; ms=seed ms= seed /*assign SEED to two REXX variables.*/
say center(' seed='seed" ", 79, '─') /*display the seed in a title/separator*/
/* [↓] show 20 rand #'s for each seed.*/
do j=1 for 20 /*obtaingenerate the& right─mostdisplay 3 digits of20 random Jnumbers.*/
 
bsd = (1103515245 * bsd + 12345) // 2**31
ms = ( bsd 214013= (1103515245 * bsd ms + 2531011) 12345) // 2**two@@31
say ' state' rightms = (j,3) " BSD"214013 * right(bsd,ms + 11 2531011) left('',// 13), two@@31
" MS" right( ms, 11) left('',/* 5),↑ */
" rand" right(ms%2 /**16, 6) └─────◄──── REXX remainder operator*/
 
end /*j*/
end /*seed*/ say ' state' right(j,3) " BSD" right(bsd, 11) left('', /*stick a fork in it13), we're all done. */</lang>
" MS" right( ms, 11) left('', 5),
" rand" right(ms % two@@16, 6)
end /*j*/
end /*seed*/ /*stick a fork in it, we're all done. */</syntaxhighlight>
{{out|output|text= &nbsp; &nbsp; (shown at five-sixth size.) }}
<pre style="font-size:84%">
─────────────────────────────────── seed=0 ────────────────────────────────────
────────────────────────────────────seed=0─────────────────────────────────────
state 1 BSD 12345 MS 2531011 rand 38
state 2 BSD 1406932606 MS 505908858 rand 7719
Line 2,382 ⟶ 3,116:
state 19 BSD 996984527 MS 196417061 rand 2997
state 20 BSD 1157490780 MS 962080852 rand 14680
─────────────────────────────────── seed=1 ────────────────────────────────────
────────────────────────────────────seed=1─────────────────────────────────────
state 1 BSD 1103527590 MS 2745024 rand 41
state 2 BSD 377401575 MS 1210316419 rand 18467
Line 2,403 ⟶ 3,137:
state 19 BSD 1647418052 MS 316395082 rand 4827
state 20 BSD 1675546029 MS 356309989 rand 5436
</pre>
 
=={{header|RPL}}==
≪ #1103515245d <span style="color:green">STATE</span> * #12345d + #2147483647d AND
DUP '<span style="color:green">STATE</span>' STO B→R
≫ '<span style="color:blue">?BSD</span>' STO
≪ #214013d <span style="color:green">STATE</span> * #2531011d + #2147483647d AND
DUP '<span style="color:green">STATE</span>' STO SRB SRB B→R
≫ '<span style="color:blue">?MS</span>' STO
≪ { } 0 '<span style="color:green">STATE</span>' STO
1 5 '''START''' OVER EVAL + '''NEXT'''
SWAP DROP
≫ '<span style="color:blue">TEST5</span>' STO
 
≪ <span style="color:blue">?BSD</span> ≫ <span style="color:blue">TEST5</span>
≪ <span style="color:blue">?MS</span> ≫ <span style="color:blue">TEST5</span>
{{out}}
<pre>
2: { 12345 1406932606 654583775 1449466924 229283573 }
1: { 38 7719 21238 2437 8855 }
</pre>
 
Line 2,408 ⟶ 3,164:
You can create multiple instances of LCG::Berkeley or LCG::Microsoft. Each instance privately keeps the original seed in @seed, and the current state in @r. Each class resembles the core Random class, but with fewer features. The .new method takes a seed. The #rand method returns the next random number. The #seed method returns the original seed.
 
<langsyntaxhighlight lang="ruby">module LCG
module Common
# The original seed of this generator.
Line 2,437 ⟶ 3,193:
end
end
end</langsyntaxhighlight>
 
The next example sets the seed to 1, and prints the first 5 random numbers.
 
<langsyntaxhighlight lang="ruby">lcg = LCG::Berkeley.new(1)
p (1..5).map {lcg.rand}
# prints [1103527590, 377401575, 662824084, 1147902781, 2035015474]
Line 2,447 ⟶ 3,203:
lcg = LCG::Microsoft.new(1)
p (1..5).map {lcg.rand}
# prints [41, 18467, 6334, 26500, 19169]</langsyntaxhighlight>
 
 
=={{header|Run BASIC}}==
<langsyntaxhighlight lang="runbasic">global bsd
global ms
print "Num ___Bsd___";chr$(9);"__Ms_"
Line 2,466 ⟶ 3,221:
ms = (214013 * ms + 2531011) mod (2 ^ 31)
msRnd = int(ms / 2 ^ 16)
end function</langsyntaxhighlight>
<pre>
Num ___Bsd___ __Ms_
Line 2,479 ⟶ 3,234:
9 794471793 10450
10 551188310 30612</pre>
 
 
=={{header|Rust}}==
<langsyntaxhighlight lang="rust">extern crate rand;
 
pub use rand::{Rng, SeedableRng};
Line 2,552 ⟶ 3,306:
println!("{}", ms.gen::<bool>());
println!("{}", ms.gen_ascii_chars().take(15).collect::<String>());
}</langsyntaxhighlight>
 
=={{header|Scala}}==
<langsyntaxhighlight lang="scala">object LinearCongruentialGenerator {
def bsdRandom(rseed:Int):Iterator[Int]=new Iterator[Int]{
var seed=rseed
Line 2,579 ⟶ 3,333:
println("MS : "+ toString( msRandom(1)))
}
}</langsyntaxhighlight>
{{out}}
<pre>-- seed 0 --
Line 2,598 ⟶ 3,352:
 
=={{header|Scheme}}==
For R7RS Scheme.
<lang scheme>(define ((bsd-rand seed)) (set! seed (remainder (+ (* 1103515245 seed) 12345) 2147483648)) seed)
<syntaxhighlight lang="scheme">(import (scheme base)
(scheme write))
 
(define ((bsd-rand state))
(define ((msvcrt-rand seed)) (set! seed (remainder (+ (* 214013 seed) 2531011) 2147483648)) (quotient seed 65536))
(set! state (remainder (+ (* 1103515245 state) 12345) 2147483648))
state)
 
(define ((msvcrt-rand state))
(set! state (remainder (+ (* 214013 state) 2531011) 2147483648))
(quotient state 65536))
 
; auxiliary function to get a list of 'n random numbers from generator 'r
(define (rand-list r n) = (if (zero? n) '() (cons (r) (rand-list r (- n 1)))))
(if (zero? n) '() (cons (r) (rand-list r (- n 1)))))
 
(display (rand-list (bsd-rand 0) 10))
; (12345 1406932606 654583775 1449466924 229283573 1109335178 1051550459 1293799192 794471793 551188310)
 
(newline)
(rand-list (msvcrt-rand 0) 10)
 
; (38 7719 21238 2437 8855 11797 8365 32285 10450 30612)</lang>
(display (rand-list (msvcrt-rand 0) 10))
; (38 7719 21238 2437 8855 11797 8365 32285 10450 30612)</syntaxhighlight>
 
=={{header|Seed7}}==
Line 2,619 ⟶ 3,384:
[http://seed7.sourceforge.net/libraries/array.htm#rand%28in_arrayType%29 rand(arr)]. This function selects a random element from an array.
 
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
include "bigint.s7i";
 
Line 2,649 ⟶ 3,414:
writeln(bsdRand lpad 12 <& msRand lpad 12);
end for;
end func;</langsyntaxhighlight>
 
Output:
Line 2,669 ⟶ 3,434:
Uses the Random library provided by SequenceL to create new Random Number Generators
 
<syntaxhighlight lang="sequencel">
<lang sequenceL>
import <Utilities/Random.sl>;
 
Line 2,696 ⟶ 3,461:
(Value : newSeed / 65536,
Generator : (Seed : newSeed, RandomMin : RG.RandomMin, RandomMax : RG.RandomMax, NextFunction : RG.NextFunction));
</syntaxhighlight>
</lang>
Output
<pre>
Line 2,702 ⟶ 3,467:
MS Values: [38,7719,21238,2437,8855,11797,8365,32285,10450,30612]
</pre>
 
=={{header|Sidef}}==
{{trans|Ruby}}
<langsyntaxhighlight lang="ruby">module LCG {
 
# Creates a linear congruential generator and remembers the initial seed.
Line 2,733 ⟶ 3,499:
 
var lcg2 = LCG::Microsoft(1)
say 5.of { lcg2.rand }</langsyntaxhighlight>
{{out}}
<pre>
Line 2,741 ⟶ 3,507:
 
=={{header|Sparkling}}==
<langsyntaxhighlight lang="sparkling">var states = {
"BSD": 0,
"MS": 0
Line 2,760 ⟶ 3,526:
function Microsoft_rand() {
return (states.MS = (214013 * states.MS + 2531011) % (1 << 31)) % (1 << 15);
}</langsyntaxhighlight>
 
Output seen after seeding both generators with 0:
 
<langsyntaxhighlight lang="sparkling">spn:8> Microsoft_seed(0);
spn:9> Microsoft_rand()
= 7875
Line 2,785 ⟶ 3,551:
= 1449466924
spn:19> BSD_rand()
= 229283573</langsyntaxhighlight>
 
=={{header|Standard ML}}==
<syntaxhighlight lang="sml">local
open Word32
in
fun bsdLcg (seed : int) : int =
toInt (andb (0w1103515245 * fromInt seed + 0w12345, 0wx7fffffff))
fun mscLcg (seed : word) : int * word =
let
val state = andb (0w214013 * seed + 0w2531011, 0wx7fffffff)
in
(toInt (>> (state, 0w16)), state)
end
end</syntaxhighlight>
;Test code<nowiki>:</nowiki>
<syntaxhighlight lang="sml">fun test1 rand =
(print (" " ^ Int.toString rand); rand)
 
fun test2 (rand, state) =
(print (" " ^ Int.toString rand); state)
 
fun doTimes (_, 0, state) = ()
| doTimes (f, n, state) = doTimes (f, n - 1, f state)
 
val () = print "BSD:\n"
val () = doTimes (test1 o bsdLcg, 7, 0)
val () = print "\nMSC:\n"
val () = doTimes (test2 o mscLcg, 7, 0w0)
val () = print "\n"</syntaxhighlight>
{{out}}
<pre>BSD:
12345 1406932606 654583775 1449466924 229283573 1109335178 1051550459
MSC:
38 7719 21238 2437 8855 11797 8365</pre>
 
=={{header|Stata}}==
 
<langsyntaxhighlight lang="stata">mata
function rand_bsd(u) {
m = 65536
Line 2,813 ⟶ 3,613:
 
rand_seq(&rand_bsd(),1,10)
rand_seq(&rand_ms(),0,10)</langsyntaxhighlight>
 
'''Output''': compare with OEIS '''[http://oeis.org/A096553 A096553]''' and '''[http://oeis.org/A096558 A096558]'''.
Line 2,848 ⟶ 3,648:
=={{header|Swift}}==
 
<langsyntaxhighlight Swiftlang="swift">import Cocoa
 
class LinearCongruntialGenerator {
Line 2,894 ⟶ 3,694:
{
print(BSDLinearCongruntialGenerator.random())
}</langsyntaxhighlight>
{{out}}<pre>Microsft Rand:
38
Line 2,921 ⟶ 3,721:
=={{header|Tcl}}==
Using an object-oriented solution, inspired by (but not a translation of) the [[#Ruby|Ruby]] solution above.
<langsyntaxhighlight lang="tcl">package require Tcl 8.6
 
# General form of a linear-congruential RNG
Line 2,950 ⟶ 3,750:
next $initialSeed 214013 2531011 [expr {2**31}] [expr {2**16}]
}
}</langsyntaxhighlight>
Demo code:
<langsyntaxhighlight lang="tcl">proc sample rng {foreach - {1 2 3 4 5} {lappend r [$rng rand]}; join $r ", "}
puts BSD:\t\[[sample [BSDRNG new 1]]\]
puts MS:\t\[[sample [MSRNG new 1]]\]</langsyntaxhighlight>
Output:
<pre>
Line 2,963 ⟶ 3,763:
=={{header|uBasic/4tH}}==
uBasic is an integer BASIC without any bitwise operations. That's why a trick is used when it enters the negative domain. Unfortunately, it is not portable and must be adjusted for different integer widths. This 32-bit version produces the proper result, though.
<syntaxhighlight lang="text">w = 32 ' Change for different integer size
b = 0 ' Initial BSD seed
m = 0 ' Initial MS seed
Line 2,997 ⟶ 3,797:
m = Pop() % (2 ^ 31) ' Now we got a number less than 2^31
Push m / (2 ^ 16) ' So we can complete the operation
Return</langsyntaxhighlight>
{{out}}
<pre>BSD
Line 3,028 ⟶ 3,828:
=={{header|UNIX Shell}}==
 
<langsyntaxhighlight lang="bash">#! /bin/bash
 
function BSD() {
Line 3,052 ⟶ 3,852:
 
output BSD
output MS</langsyntaxhighlight>
 
{{out}}
Line 3,080 ⟶ 3,880:
30612
 
</pre>
 
=={{header|VBA}}==
<syntaxhighlight lang="vb">Public stateBSD As Variant
Public stateMS As Variant
Private Function bsd() As Long
Dim temp As Variant
temp = CDec(1103515245 * stateBSD + 12345)
temp2 = temp / 2 ^ 31
temp3 = CDec(WorksheetFunction.Floor_Precise(temp2))
stateBSD = temp - (2 ^ 31) * temp3
bsd = stateBSD
End Function
Private Function ms() As Integer
Dim temp As Variant
temp = CDec(214013 * stateMS + 2531011)
temp2 = temp / 2 ^ 31
temp3 = CDec(WorksheetFunction.Floor_Precise(temp2))
stateMS = temp - (2 ^ 31) * temp3
ms = stateMS \ 2 ^ 16
End Function
Public Sub main()
stateBSD = CDec(0)
stateMS = CDec(0)
Debug.Print " BSD", " MS"
For i = 1 To 10
Debug.Print Format(bsd, "@@@@@@@@@@"), Format(ms, "@@@@@")
Next i
End Sub</syntaxhighlight>{{out}}
<pre> BSD MS
12345 38
1406932606 7719
654583775 21238
1449466924 2437
229283573 8855
1109335178 11797
1051550459 8365
1293799192 32285
794471793 10450
551188310 30612</pre>
 
=={{header|Wren}}==
{{trans|Go}}
{{libheader|Wren-big}}
{{libheader|Wren-fmt}}
Some of the intermediate calculations here require integers >= 2^53 so we need to use BigInt.
<syntaxhighlight lang="wren">import "./big" for BigInt
import "./fmt" for Fmt
 
// basic linear congruential generator
var lcg = Fn.new { |a, c, m, seed|
var r = BigInt.new(seed)
return Fn.new {
r = (r*a + c) % m
return r
}
}
 
// Microsoft generator has extra division step
var msg = Fn.new { |seed|
var g = lcg.call(214013, 2531011, 1<<31, seed)
return Fn.new { g.call()/(1 << 16) }
}
 
var example = Fn.new { |seed|
System.print("\nWith seed = %(seed):")
var bsd = lcg.call(1103515245, 12345, 1<<31, seed)
var msf = msg.call(seed)
System.print(" BSD MSF")
for (i in 0..4) {
Fmt.print("$10i $5i", bsd.call(), msf.call())
}
}
 
example.call(0)
example.call(1)</syntaxhighlight>
 
{{out}}
<pre>
With seed = 0:
BSD MSF
12345 38
1406932606 7719
654583775 21238
1449466924 2437
229283573 8855
 
With seed = 1:
BSD MSF
1103527590 41
377401575 18467
662824084 6334
1147902781 26500
2035015474 19169
</pre>
 
Line 3,087 ⟶ 3,981:
 
First example using integer instructions.
<langsyntaxhighlight lang="asm">;x86-64 assembly code for Microsoft Windows
;Tested in windows 7 Enterprise Service Pack 1 64 bit
;With the AMD FX(tm)-6300 processor
Line 3,274 ⟶ 4,168:
 
mov rcx,1
call exit</langsyntaxhighlight>
 
Second example using AVX instructions.
{{incorrect|X86 Assembly|It will not produce output identical to that of the Microsoft rand() function.}}
<langsyntaxhighlight lang="asm">;x86-64 assembly code for Microsoft Windows
;Tested in windows 7 Enterprise Service Pack 1 64 bit
;With the AMD FX(tm)-6300 processor
Line 3,521 ⟶ 4,415:
 
mov rcx,1
call exit</langsyntaxhighlight>
 
{{out|Sample}}
Line 3,583 ⟶ 4,477:
[[File:LCG2XPL0.gif|right]]
 
<langsyntaxhighlight XPL0lang="xpl0">include c:\cxpl\codes;
int R;
 
Line 3,611 ⟶ 4,505:
N:= ChIn(1); \wait for keystoke
SetVid(3); \restore normal text mode
]</langsyntaxhighlight>
 
=={{header|zkl}}==
<langsyntaxhighlight lang="zkl">var [private] seed = 0;
fcn srand(s){ seed = s }
 
Line 3,627 ⟶ 4,521:
const A=214013, C=2531011, TWO16=(1).shiftLeft(16);
fcn rand{ (seed = (seed * A + C) % TWO31) / TWO16 }
#endif</langsyntaxhighlight>
<langsyntaxhighlight lang="zkl">srand(0);
println(rand(),",",rand(),",",rand());</langsyntaxhighlight>
{{out}}
<pre>
1,972

edits