Linear congruential generator: Difference between revisions
Added Easylang
(Added Easylang) |
|||
(38 intermediate revisions by 21 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:
* <math>r_{n + 1} = a \times r_n + c \pmod m</math>
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:
* <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:
* <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]].
<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}}==
<
LINCONG CSECT
USING LINCONG,R12
Line 70 ⟶ 118:
XDEC DS CL12
YREGS
END LINCONG</
{{out}}
<pre>
Line 89 ⟶ 137:
We first specify a generic package LCG:
<
type Base_Type is mod <>;
Multiplyer, Adder: Base_Type;
Line 99 ⟶ 147:
-- changes the state and outputs the result
end LCG;</
Then we provide a generic implementation:
<
State: Base_Type := Base_Type'First;
Line 118 ⟶ 166:
end Random;
end LCG;</
Next, we define the MS- and BSD-instantiations of the generic package:
<
procedure Run_LCGs is
Line 141 ⟶ 189:
Ada.Text_IO.Put_Line(M31'Image(MS_Rand.Random));
end loop;
end Run_LCGs;</
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}}==
<
BEGIN
COMMENT
Line 247 ⟶ 295:
srand (0)
END
</syntaxhighlight>
{{out}}
<pre>
Line 274 ⟶ 322:
=={{header|AutoHotkey}}==
<
Loop, 10
BSD .= "`t" (a := BSD(a)) "`n"
Line 289 ⟶ 337:
Seed := Mod(214013 * Seed + 2531011, 2147483648)
return, [Seed, Seed // 65536]
}</
'''Output:'''
<pre>BSD:
Line 315 ⟶ 363:
30612</pre>
=={{header|Batch File}}==
<syntaxhighlight lang="dos">@echo off & setlocal enabledelayedexpansion
echo BSD Rand
Line 340 ⟶ 387:
set p2= %2
echo %p1:~-2% %p2:~-10%
goto:eof</syntaxhighlight>
'''Output:'''
<pre>
Line 371 ⟶ 416:
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<
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%</
'''Output:'''
<pre>
Line 438 ⟶ 483:
As with dc, bc has no bitwise operators.
<
define rand() {
Line 456 ⟶ 501:
randseed = 1
rand(); rand(); rand(); print "\n"</
=={{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.
<
v $$_^#!\-1:\%***:*::*882 ++*"yf"3***+***+*<
>025*>\:488**:*/:0\`6"~7"+:*+01-2/-*+."O?+"55v
@ $$_^#!\-1:\%***:*::*882 ++***" ''4C"*+2**,+<</
{{out}}
Line 491 ⟶ 536:
=={{header|Bracmat}}==
<
& 2^-16:?rshift
& (randBSD=mod$(!seed*1103515245+12345.!RANDMAX):?seed)
Line 506 ⟶ 551:
& 0:?i
& whl'(1+!i:~>10:?i&out$!randMS)
)</
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.
<
/* always assuming int is at least 32 bits */
Line 575 ⟶ 620:
return 0;
}</
=={{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++}}==
<
//--------------------------------------------------------------------------------------------------
Line 628 ⟶ 832:
return 0;
}
//--------------------------------------------------------------------------------------------------</
Output:
<pre>
Line 660 ⟶ 864:
; C++11
{{works with|C++11}}
<
#include <random>
Line 679 ⟶ 883:
return 0;
}</
Output:
<pre>
Line 711 ⟶ 915:
=={{header|Clojure}}==
<syntaxhighlight lang="clojure">
(defn iterator [a b]
Line 723 ⟶ 927:
(take 10 ms) ;-> (38 7719 21238 2437 8855 11797 8365 32285 10450 30612)
</syntaxhighlight>
=={{header|Common Lisp}}==
<
"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))))</
Another solution could be:
<
(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))</
Which defaults to the BSD formula, but can be customized to any formula with keyword arguments, for example:
<
(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)))))</
Outputs:
Line 764 ⟶ 968:
4 229283573 8855
5 1109335178 11797</pre>
=={{header|D}}==
<
enum uint RAND_MAX = (1U << 31) - 1;
uint seed = 0;
Line 952 ⟶ 997:
foreach (immutable i; 0 .. 10)
writeln(rnd.randMS);
}</
Output:
<pre>12345
Line 979 ⟶ 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(): <
* lrx -- (random number from 0 to 2147483647)
*
Line 989 ⟶ 1,034:
[* Set seed to 1, then print the first 3 random numbers. *]sz
1 sR
lrx psz lrx psz lrx psz</
<pre>1103527590
Line 995 ⟶ 1,040:
662824084</pre>
For Microsoft rand(): <
* lrx -- (random number from 0 to 32767)
*
Line 1,005 ⟶ 1,050:
[* Set seed to 1, then print the first 3 random numbers. *]sz
1 sR
lrx psz lrx psz lrx psz</
<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}}==
<
def ms_seed(seed) do
Process.put(:ms_state, seed)
Line 1,046 ⟶ 1,401:
:io.format "~11w~8w~n", [LCG.bsd_rand, LCG.ms_rand]
end)
end)</
{{out}}
Line 1,079 ⟶ 1,434:
=={{header|Erlang}}==
{{trans|Elixir}}
<
-export([bsd_seed/1, ms_seed/1, bsd_rand/0, ms_rand/0]).
Line 1,099 ⟶ 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)).</
{{Out}}
Line 1,116 ⟶ 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).
<
!$DOUBLE
Line 1,149 ⟶ 1,504:
PRINT(TAB(10);XRND)
END FOR
END PROGRAM</
{{out}}
<pre>
Line 1,178 ⟶ 1,533:
=={{header|F_Sharp|F#}}==
<
let bsd seed =
let state = ref seed
Line 1,190 ⟶ 1,545:
state := (214013 * !state + 2531011) &&& System.Int32.MaxValue
!state / (1<<<16))
</syntaxhighlight>
<pre>let rndBSD = lcg.bsd 0;;
let BSD=[for n in [0 .. 9] -> rndBSD()];;
Line 1,202 ⟶ 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}}==
<
1 15 lshift 1- constant MAX-RAND-MS
Line 1,220 ⟶ 1,610:
;
test-random</
Output:
Line 1,239 ⟶ 1,629:
=={{header|Fortran}}==
{{works with|Fortran|90 and later}}
<
implicit none
Line 1,280 ⟶ 1,670:
write(*, "(2i12)") bsdrand(), msrand()
end do
end program</
Output
<pre> BSD MS
Line 1,293 ⟶ 1,683:
794471793 10450
551188310 30612</pre>
=={{header|FreeBASIC}}==
<
' compile with: fbc -s console
Line 1,350 ⟶ 1,741:
Print : Print "hit any key to end program"
Sleep
End</
{{out}}
<pre>MS generator
Line 1,375 ⟶ 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}}==
<
import "fmt"
Line 1,411 ⟶ 1,820:
example(0)
example(1)
}</
Output:
<pre>
Line 1,432 ⟶ 1,841:
=={{header|Haskell}}==
<
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</
=={{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.
<
procedure main()
Line 1,465 ⟶ 1,874:
procedure rand_MS() #: lcrng
return ishift(srand_MS((214013 * srand_MS() + 2531011) % 2147483648),-16)
end</
{{libheader|Icon Programming Library}}
Line 1,472 ⟶ 1,881:
=={{header|J}}==
'''Solution:'''
<
0 m lcg y NB. default seed of 0
:
Line 1,480 ⟶ 1,889:
rand_bsd=: (1103515245 12345 , <.2^31) lcg
rand_ms=: (2^16) <.@:%~ (214013 2531011 , <.2^31) lcg</
'''Example Use:'''
<
12345 1406932606 654583775 1449466924 229283573 1109335178 1051550459 1293799192 794471793 551188310
654583775 rand_bsd 4
Line 1,489 ⟶ 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</
=={{header|Java}}==
{{works with|Java|8}}
<
import static java.util.stream.IntStream.iterate;
Line 1,515 ⟶ 1,924:
.map(i -> i >> 16);
}
}</
<pre>BSD:
Line 1,542 ⟶ 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.
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====
<
# from the Microsoft C Runtime.
# Input: [ count, state, rand ]
Line 1,557 ⟶ 1,970:
| next_rand_Microsoft # the seed is not so random
| recurse(if .[0] < n then next_rand_Microsoft else empty end)
| .[2];</
'''Example''':
rand_Microsoft(1;5)
{{out}}
<
18467
6334
26500
19169</
====BSD LCG====
The following code has been tested with the "BigInt" library at [https://gist.github.com/pkoppstein/d06a123f30c033195841].
<
# Input: [count, previous]
def next_rand_berkeley:
Line 1,581 ⟶ 1,994:
| next_rand_berkeley # skip the seed itself
| recurse(if .[0] < n then next_rand_berkeley else empty end)
| .[1];</
'''Example''':
rand_berkeley(1;5)
{{out}}
<
377401575
662824084
1147902781
2035015474</
=={{header|Julia}}==
<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
function getlgc(r::Integer, a::Integer, c::Integer, m::Integer, sh::Integer)
state = r
return function lgcrand()
Line 1,616 ⟶ 2,029:
for _ in 1:nrep
@printf("%14d\n", msrand())
end</
{{out}}
Line 1,644 ⟶ 2,057:
=={{header|K}}==
<
ms:{1_(y{_(((214013*x)+2531011)!(_2^31))}\x)%(_2^16)}
Line 1,650 ⟶ 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</
=={{header|Kotlin}}==
<
class Lcg(val a: Long, val c: Long, val m: Long, val d: Long, val s: Long) {
Line 1,671 ⟶ 2,084:
val msc = Lcg(214013, 2531011, 1 shl 31, 1 shl 16, 0)
for (i in 1..10) println("${msc.nextInt()}")
}</
{{out}}
Line 1,701 ⟶ 2,114:
=={{header|Liberty BASIC}}==
<syntaxhighlight lang="lb">
'by default these are 0
global BSDState
Line 1,725 ⟶ 2,138:
randMS = int(MSState / 2 ^ 16)
end function
</syntaxhighlight>
=={{header|Logo}}==
Line 1,731 ⟶ 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).
<
make "LCG_MS [214013 2531011 65536 2147483648]
make "LCG_BSD [1103515245 12345 1 2147483648]
Line 1,760 ⟶ 2,173:
print []
]
bye</
Output:<pre>12345
Line 1,801 ⟶ 2,214:
This requires Lua 5.3 or later because previous versions didn't have support for large integers or integral arithmetic operations.
<
new = function(class, a, c, m, rand)
local self = setmetatable({}, class)
Line 1,827 ⟶ 2,240:
print(("\t%10d"):format(ms.rnd()))
end
</syntaxhighlight>
{{Out}}
Line 1,854 ⟶ 2,267:
</pre>
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<
NestList[BSDrand, 0, 10]
-> {0, 12345, 1406932606, 654583775, 1449466924, 229283573, 1109335178, 1051550459, 1293799192, 794471793, 551188310}
Line 1,861 ⟶ 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}</
=={{header|Maxima}}==
<
ms_rand() := quotient(seed: mod(214013 * seed + 2531011, 2147483648), 65536)$
makelist(ms_rand(), 20); /* see http://oeis.org/A096558 */
Line 1,877 ⟶ 2,290:
[12345, 1406932606, 654583775, 1449466924, 229283573, 1109335178, 1051550459,
1293799192, 794471793, 551188310, 803550167, 1772930244, 370913197, 639546082, 1381971571,
1695770928, 2121308585, 1719212846, 996984527, 1157490780]</
=={{header|Nim}}==
<
var
result = iterator: int =
while true:
yield
proc msvcrtRand(seed: int): iterator: int =
var
result = iterator: int =
while true:
yield
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,898 ⟶ 2,383:
Function genLCG returns a block object that, when performed, will return the next random number from the LCG.
<
| ch |
Channel newSize(1) dup send(seed) drop ->ch
#[ ch receive a * c + m mod dup ch send drop ] ;</
{{out}}
Line 1,932 ⟶ 2,417:
=={{header|PARI/GP}}==
Note that up to PARI/GP version 2.4.0, <code>random()</code> used a linear congruential generator.
<
MSFTseed=Mod(1,1<<31);
BSD()=BSDseed=1103515245*BSDseed+12345;lift(BSDseed);
MSFT()=MSFTseed=214013*MSFTseed+2531011;lift(MSFTseed)%(1<<31);</
=={{header|Pascal}}==
<
{$mode iso}
var
Line 1,972 ⟶ 2,457:
writeln(bsdrand:12, msrand:12);
end.
</syntaxhighlight>
Output:
<pre> BSD MS
Line 1,987 ⟶ 2,472:
=={{header|Perl}}==
Creates a magic scalar whose value is next in the LCG sequence when read.<
package LCG;
Line 2,026 ⟶ 2,511:
print "\nMS:\n";
print "$rand\n" for 1 .. 10;</
12345
1406932606
Line 2,048 ⟶ 2,533:
32285
10450
30612</
=={{header|Phix}}==
{{libheader|
As per the comments, I had to resort to
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #004080;">atom</span> <span style="color: #000000;">seed</span>
<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>
<span style="color: #008080;">function</span> <span style="color: #000000;">BSDrnd</span><span style="color: #0000FF;">()</span>
<span style="color: #000080;font-style:italic;">-- oh dear, native only works on 64-bit,
-- as per ERRE and UCBLogo above on 32-bit...
-- seed = remainder(1103515245 * seed + 12345, #8000_0000)
-- so, resort to gmp, with the added twist than both
-- therefore a smidge too big & need some extra help...</span>
<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>
<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>
<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>
<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>
<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>
<span style="color: #008080;">return</span> <span style="color: #000000;">seed</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">MSrnd</span><span style="color: #0000FF;">()</span>
<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>
<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>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</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;">"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,153 ⟶ 2,601:
=={{header|PHP}}==
{{works with|PHP|5.3+}}
<
function bsd_rand($seed) {
return function() use (&$seed) {
Line 2,177 ⟶ 2,625:
echo $lcg(), " ";
echo "\n";
?></
=={{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}}==
<
(de bsdRand ()
Line 2,189 ⟶ 2,724:
(>> 16
(setq *MsSeed
(& (+ 2531011 (* 214013 *MsSeed)) `(dec (** 2 31))) ) ) )</
Output:
<pre>: (do 7 (printsp (bsdRand)))
Line 2,198 ⟶ 2,733:
=={{header|PL/I}}==
<syntaxhighlight lang="text">
(nofixedoverflow, nosize):
LCG: procedure options (main);
Line 2,227 ⟶ 2,762:
end LCG;
</syntaxhighlight>
OUTPUT:
<pre>
Line 2,254 ⟶ 2,789:
=={{header|PowerShell}}==
<
Function msstate{
Param($current_seed)
Line 2,279 ⟶ 2,814:
$seed = randBSD($seed)
Write-Host $seed}
</syntaxhighlight>
{{Out}}
Line 2,298 ⟶ 2,833:
=={{header|PureBasic}}==
<
Static state.q
If seed >= 0
Line 2,334 ⟶ 2,869:
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
CloseConsole()
EndIf</
Sample output:
<pre>BSD (seed = 1)
Line 2,351 ⟶ 2,886:
=={{header|Python}}==
<
def rand():
rand.seed = (1103515245*rand.seed + 12345) & 0x7fffffff
Line 2,363 ⟶ 2,898:
return rand.seed >> 16
rand.seed = seed
return rand</
{{works with|Python|3.x}}
<
def rand():
nonlocal seed
Line 2,377 ⟶ 2,912:
seed = (214013*seed + 2531011) & 0x7fffffff
return seed >> 16
return rand</
=={{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,383 ⟶ 3,002:
The following solution uses generators and transcribes the mathematical formulas above directly. It does not attempt to be efficient.
<
#lang racket
(require racket/generator)
Line 2,404 ⟶ 3,023:
(define bsd-rand (rand bsd-update identity))
(define ms-rand (rand ms-update (λ (x) (quotient x (expt 2 16)))))
</syntaxhighlight>
=={{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}}==
<
/*
numeric digits 20 /*
two@@16= 2**16 /*use a variable to contain 2^16 */
two@@31= 2**31 /* " " " " " 2^32 */
say center(' seed='seed" ", 79, '─')
/* [↓] show 20 rand #'s for each seed.*/
do j=1 for 20
" 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= (shown at five-sixth size.) }}
<pre style="font-size:84%">
─────────────────────────────────── seed=0 ────────────────────────────────────
state 1 BSD 12345 MS 2531011 rand 38
state 2 BSD 1406932606 MS 505908858 rand 7719
Line 2,446 ⟶ 3,116:
state 19 BSD 996984527 MS 196417061 rand 2997
state 20 BSD 1157490780 MS 962080852 rand 14680
─────────────────────────────────── seed=1 ────────────────────────────────────
state 1 BSD 1103527590 MS 2745024 rand 41
state 2 BSD 377401575 MS 1210316419 rand 18467
Line 2,467 ⟶ 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,472 ⟶ 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.
<
module Common
# The original seed of this generator.
Line 2,501 ⟶ 3,193:
end
end
end</
The next example sets the seed to 1, and prints the first 5 random numbers.
<
p (1..5).map {lcg.rand}
# prints [1103527590, 377401575, 662824084, 1147902781, 2035015474]
Line 2,511 ⟶ 3,203:
lcg = LCG::Microsoft.new(1)
p (1..5).map {lcg.rand}
# prints [41, 18467, 6334, 26500, 19169]</
=={{header|Run BASIC}}==
<
global ms
print "Num ___Bsd___";chr$(9);"__Ms_"
Line 2,530 ⟶ 3,221:
ms = (214013 * ms + 2531011) mod (2 ^ 31)
msRnd = int(ms / 2 ^ 16)
end function</
<pre>
Num ___Bsd___ __Ms_
Line 2,543 ⟶ 3,234:
9 794471793 10450
10 551188310 30612</pre>
=={{header|Rust}}==
<
pub use rand::{Rng, SeedableRng};
Line 2,616 ⟶ 3,306:
println!("{}", ms.gen::<bool>());
println!("{}", ms.gen_ascii_chars().take(15).collect::<String>());
}</
=={{header|Scala}}==
<
def bsdRandom(rseed:Int):Iterator[Int]=new Iterator[Int]{
var seed=rseed
Line 2,643 ⟶ 3,333:
println("MS : "+ toString( msRandom(1)))
}
}</
{{out}}
<pre>-- seed 0 --
Line 2,662 ⟶ 3,352:
=={{header|Scheme}}==
For R7RS Scheme.
<syntaxhighlight lang="scheme">(import (scheme base)
(scheme write))
(define ((bsd-rand state))
(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)))))
(display (rand-list (bsd-rand 0) 10))
; (12345 1406932606 654583775 1449466924 229283573 1109335178 1051550459 1293799192 794471793 551188310)
(newline)
(display (rand-list (msvcrt-rand 0) 10))
; (38 7719 21238 2437 8855 11797 8365 32285 10450 30612)</syntaxhighlight>
=={{header|Seed7}}==
Line 2,683 ⟶ 3,384:
[http://seed7.sourceforge.net/libraries/array.htm#rand%28in_arrayType%29 rand(arr)]. This function selects a random element from an array.
<
include "bigint.s7i";
Line 2,713 ⟶ 3,414:
writeln(bsdRand lpad 12 <& msRand lpad 12);
end for;
end func;</
Output:
Line 2,733 ⟶ 3,434:
Uses the Random library provided by SequenceL to create new Random Number Generators
<syntaxhighlight lang="sequencel">
import <Utilities/Random.sl>;
Line 2,760 ⟶ 3,461:
(Value : newSeed / 65536,
Generator : (Seed : newSeed, RandomMin : RG.RandomMin, RandomMax : RG.RandomMax, NextFunction : RG.NextFunction));
</syntaxhighlight>
Output
<pre>
Line 2,766 ⟶ 3,467:
MS Values: [38,7719,21238,2437,8855,11797,8365,32285,10450,30612]
</pre>
=={{header|Sidef}}==
{{trans|Ruby}}
<
# Creates a linear congruential generator and remembers the initial seed.
Line 2,797 ⟶ 3,499:
var lcg2 = LCG::Microsoft(1)
say 5.of { lcg2.rand }</
{{out}}
<pre>
Line 2,805 ⟶ 3,507:
=={{header|Sparkling}}==
<
"BSD": 0,
"MS": 0
Line 2,824 ⟶ 3,526:
function Microsoft_rand() {
return (states.MS = (214013 * states.MS + 2531011) % (1 << 31)) % (1 << 15);
}</
Output seen after seeding both generators with 0:
<
spn:9> Microsoft_rand()
= 7875
Line 2,849 ⟶ 3,551:
= 1449466924
spn:19> BSD_rand()
= 229283573</
=={{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}}==
<
function rand_bsd(u) {
m = 65536
Line 2,877 ⟶ 3,613:
rand_seq(&rand_bsd(),1,10)
rand_seq(&rand_ms(),0,10)</
'''Output''': compare with OEIS '''[http://oeis.org/A096553 A096553]''' and '''[http://oeis.org/A096558 A096558]'''.
Line 2,912 ⟶ 3,648:
=={{header|Swift}}==
<
class LinearCongruntialGenerator {
Line 2,958 ⟶ 3,694:
{
print(BSDLinearCongruntialGenerator.random())
}</
{{out}}<pre>Microsft Rand:
38
Line 2,985 ⟶ 3,721:
=={{header|Tcl}}==
Using an object-oriented solution, inspired by (but not a translation of) the [[#Ruby|Ruby]] solution above.
<
# General form of a linear-congruential RNG
Line 3,014 ⟶ 3,750:
next $initialSeed 214013 2531011 [expr {2**31}] [expr {2**16}]
}
}</
Demo code:
<
puts BSD:\t\[[sample [BSDRNG new 1]]\]
puts MS:\t\[[sample [MSRNG new 1]]\]</
Output:
<pre>
Line 3,027 ⟶ 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 3,061 ⟶ 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</
{{out}}
<pre>BSD
Line 3,092 ⟶ 3,828:
=={{header|UNIX Shell}}==
<
function BSD() {
Line 3,116 ⟶ 3,852:
output BSD
output MS</
{{out}}
Line 3,147 ⟶ 3,883:
=={{header|VBA}}==
<
Public stateMS As Variant
Private Function bsd() As Long
Line 3,172 ⟶ 3,908:
Debug.Print Format(bsd, "@@@@@@@@@@"), Format(ms, "@@@@@")
Next i
End Sub</
<pre> BSD MS
12345 38
Line 3,184 ⟶ 3,920:
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>
=={{header|X86 Assembly}}==
Line 3,189 ⟶ 3,981:
First example using integer instructions.
<
;Tested in windows 7 Enterprise Service Pack 1 64 bit
;With the AMD FX(tm)-6300 processor
Line 3,376 ⟶ 4,168:
mov rcx,1
call exit</
Second example using AVX instructions.
{{incorrect|X86 Assembly|It will not produce output identical to that of the Microsoft rand() function.}}
<
;Tested in windows 7 Enterprise Service Pack 1 64 bit
;With the AMD FX(tm)-6300 processor
Line 3,623 ⟶ 4,415:
mov rcx,1
call exit</
{{out|Sample}}
Line 3,685 ⟶ 4,477:
[[File:LCG2XPL0.gif|right]]
<
int R;
Line 3,713 ⟶ 4,505:
N:= ChIn(1); \wait for keystoke
SetVid(3); \restore normal text mode
]</
=={{header|zkl}}==
<
fcn srand(s){ seed = s }
Line 3,729 ⟶ 4,521:
const A=214013, C=2531011, TWO16=(1).shiftLeft(16);
fcn rand{ (seed = (seed * A + C) % TWO31) / TWO16 }
#endif</
<
println(rand(),",",rand(),",",rand());</
{{out}}
<pre>
|