Linear congruential generator: Difference between revisions

Content added Content deleted
m (syntax highlighting fixup automation)
Line 39: Line 39:


=={{header|11l}}==
=={{header|11l}}==
<lang 11l>T LinearCongruentialGenerator
<syntaxhighlight lang="11l">T LinearCongruentialGenerator
seed = 0
seed = 0
Int a, c, m
Int a, c, m
Line 61: Line 61:
print(‘MS RAND:’)
print(‘MS RAND:’)
L 5
L 5
print(ms_rnd() >> 16)</lang>
print(ms_rnd() >> 16)</syntaxhighlight>


{{out}}
{{out}}
Line 81: Line 81:


=={{header|360 Assembly}}==
=={{header|360 Assembly}}==
<lang 360asm>* Linear congruential generator 07/03/2017
<syntaxhighlight lang="360asm">* Linear congruential generator 07/03/2017
LINCONG CSECT
LINCONG CSECT
USING LINCONG,R12
USING LINCONG,R12
Line 118: Line 118:
XDEC DS CL12
XDEC DS CL12
YREGS
YREGS
END LINCONG</lang>
END LINCONG</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 137: Line 137:
We first specify a generic package LCG:
We first specify a generic package LCG:


<lang Ada>generic
<syntaxhighlight lang="ada">generic
type Base_Type is mod <>;
type Base_Type is mod <>;
Multiplyer, Adder: Base_Type;
Multiplyer, Adder: Base_Type;
Line 147: Line 147:
-- changes the state and outputs the result
-- changes the state and outputs the result


end LCG;</lang>
end LCG;</syntaxhighlight>


Then we provide a generic implementation:
Then we provide a generic implementation:


<lang Ada>package body LCG is
<syntaxhighlight lang="ada">package body LCG is


State: Base_Type := Base_Type'First;
State: Base_Type := Base_Type'First;
Line 166: Line 166:
end Random;
end Random;


end LCG;</lang>
end LCG;</syntaxhighlight>


Next, we define the MS- and BSD-instantiations of the generic package:
Next, we define the MS- and BSD-instantiations of the generic package:


<lang Ada>with Ada.Text_IO, LCG;
<syntaxhighlight lang="ada">with Ada.Text_IO, LCG;


procedure Run_LCGs is
procedure Run_LCGs is
Line 189: Line 189:
Ada.Text_IO.Put_Line(M31'Image(MS_Rand.Random));
Ada.Text_IO.Put_Line(M31'Image(MS_Rand.Random));
end loop;
end loop;
end Run_LCGs;</lang>
end Run_LCGs;</syntaxhighlight>


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):
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 215: Line 215:


=={{header|ALGOL 68}}==
=={{header|ALGOL 68}}==
<lang algol68>
<syntaxhighlight lang="algol68">
BEGIN
BEGIN
COMMENT
COMMENT
Line 295: Line 295:
srand (0)
srand (0)
END
END
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 322: Line 322:


=={{header|AutoHotkey}}==
=={{header|AutoHotkey}}==
<lang AutoHotkey>a := 0, b:= [0]
<syntaxhighlight lang="autohotkey">a := 0, b:= [0]
Loop, 10
Loop, 10
BSD .= "`t" (a := BSD(a)) "`n"
BSD .= "`t" (a := BSD(a)) "`n"
Line 337: Line 337:
Seed := Mod(214013 * Seed + 2531011, 2147483648)
Seed := Mod(214013 * Seed + 2531011, 2147483648)
return, [Seed, Seed // 65536]
return, [Seed, Seed // 65536]
}</lang>
}</syntaxhighlight>
'''Output:'''
'''Output:'''
<pre>BSD:
<pre>BSD:
Line 364: Line 364:


=={{header|Batch}}==
=={{header|Batch}}==
<lang batch>
<syntaxhighlight lang="batch">
@echo off & setlocal enabledelayedexpansion
@echo off & setlocal enabledelayedexpansion


Line 390: Line 390:
goto:eof
goto:eof
</syntaxhighlight>
</lang>
'''Output:'''
'''Output:'''
<pre>
<pre>
Line 419: Line 419:
=={{header|BBC BASIC}}==
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
{{works with|BBC BASIC for Windows}}
<lang bbcbasic> @% = &D0D
<syntaxhighlight lang="bbcbasic"> @% = &D0D
PRINT "MS generator:"
PRINT "MS generator:"
dummy% = FNrandMS(0)
dummy% = FNrandMS(0)
Line 452: Line 452:
DEF FNmuladd(A%,B%,C%) : PRIVATE M% : LOCAL P% : IF M% = 0 DIM P% 8
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 :]
IF P% THEN [OPT 0 : .M% mul ebx : add eax,ecx : btr eax,31 : ret :]
= USR M%</lang>
= USR M%</syntaxhighlight>
'''Output:'''
'''Output:'''
<pre>
<pre>
Line 486: Line 486:


As with dc, bc has no bitwise operators.
As with dc, bc has no bitwise operators.
<lang bc>/* BSD rand */
<syntaxhighlight lang="bc">/* BSD rand */


define rand() {
define rand() {
Line 504: Line 504:


randseed = 1
randseed = 1
rand(); rand(); rand(); print "\n"</lang>
rand(); rand(); rand(); print "\n"</syntaxhighlight>


=={{header|Befunge}}==
=={{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.
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.


<lang befunge>>025*>\::0\`288*::*:****+.55+,"iQ"5982156*:v
<syntaxhighlight lang="befunge">>025*>\::0\`288*::*:****+.55+,"iQ"5982156*:v
v $$_^#!\-1:\%***:*::*882 ++*"yf"3***+***+*<
v $$_^#!\-1:\%***:*::*882 ++*"yf"3***+***+*<
>025*>\:488**:*/:0\`6"~7"+:*+01-2/-*+."O?+"55v
>025*>\:488**:*/:0\`6"~7"+:*+01-2/-*+."O?+"55v
@ $$_^#!\-1:\%***:*::*882 ++***" ''4C"*+2**,+<</lang>
@ $$_^#!\-1:\%***:*::*882 ++***" ''4C"*+2**,+<</syntaxhighlight>


{{out}}
{{out}}
Line 539: Line 539:


=={{header|Bracmat}}==
=={{header|Bracmat}}==
<lang bracmat>( 2^31:?RANDMAX
<syntaxhighlight lang="bracmat">( 2^31:?RANDMAX
& 2^-16:?rshift
& 2^-16:?rshift
& (randBSD=mod$(!seed*1103515245+12345.!RANDMAX):?seed)
& (randBSD=mod$(!seed*1103515245+12345.!RANDMAX):?seed)
Line 554: Line 554:
& 0:?i
& 0:?i
& whl'(1+!i:~>10:?i&out$!randMS)
& whl'(1+!i:~>10:?i&out$!randMS)
)</lang>
)</syntaxhighlight>


Output:
Output:
Line 583: Line 583:
=={{header|C}}==
=={{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.
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.
<lang C>#include <stdio.h>
<syntaxhighlight lang="c">#include <stdio.h>


/* always assuming int is at least 32 bits */
/* always assuming int is at least 32 bits */
Line 623: Line 623:


return 0;
return 0;
}</lang>
}</syntaxhighlight>


=={{header|C sharp|C#}}==
=={{header|C sharp|C#}}==
{{works with|C sharp|C#|6+}}
{{works with|C sharp|C#|6+}}
<!-- By Martin Freedman, 17/01/2018 -->
<!-- By Martin Freedman, 17/01/2018 -->
<lang Csharp>using System;
<syntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
using System.Collections.Generic;
using System.Linq;
using System.Linq;
Line 663: Line 663:
}
}
}
}
}</lang>
}</syntaxhighlight>
Produces:
Produces:
<pre>BSD next 10 Random
<pre>BSD next 10 Random
Line 689: Line 689:
</pre>
</pre>
From a Free Cell Deal solution
From a Free Cell Deal solution
<syntaxhighlight lang="csharp">
<lang Csharp>
using System;
using System;
using System.Collections.Generic;
using System.Collections.Generic;
Line 757: Line 757:
}
}
}
}
</syntaxhighlight>
</lang>
Output:
Output:
<pre>Microsoft
<pre>Microsoft
Line 785: Line 785:


=={{header|C++}}==
=={{header|C++}}==
<lang cpp>#include <iostream>
<syntaxhighlight lang="cpp">#include <iostream>


//--------------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------------
Line 835: Line 835:
return 0;
return 0;
}
}
//--------------------------------------------------------------------------------------------------</lang>
//--------------------------------------------------------------------------------------------------</syntaxhighlight>
Output:
Output:
<pre>
<pre>
Line 867: Line 867:
; C++11
; C++11
{{works with|C++11}}
{{works with|C++11}}
<lang cpp>#include <iostream>
<syntaxhighlight lang="cpp">#include <iostream>
#include <random>
#include <random>


Line 886: Line 886:
return 0;
return 0;
}</lang>
}</syntaxhighlight>
Output:
Output:
<pre>
<pre>
Line 918: Line 918:
=={{header|Clojure}}==
=={{header|Clojure}}==


<syntaxhighlight lang="clojure">
<lang Clojure>


(defn iterator [a b]
(defn iterator [a b]
Line 930: Line 930:
(take 10 ms) ;-> (38 7719 21238 2437 8855 11797 8365 32285 10450 30612)
(take 10 ms) ;-> (38 7719 21238 2437 8855 11797 8365 32285 10450 30612)


</syntaxhighlight>
</lang>


=={{header|Common Lisp}}==
=={{header|Common Lisp}}==
<lang lisp>(defun make-rng (&key (seed 0) (mode nil))
<syntaxhighlight lang="lisp">(defun make-rng (&key (seed 0) (mode nil))
"returns an RNG according to :seed and :mode keywords
"returns an RNG according to :seed and :mode keywords
default mode: bsd
default mode: bsd
Line 946: Line 946:


(let ((rng (make-rng :mode 'ms :seed 1)))
(let ((rng (make-rng :mode 'ms :seed 1)))
(dotimes (x 10) (format t "MS: ~d~%" (funcall rng))))</lang>
(dotimes (x 10) (format t "MS: ~d~%" (funcall rng))))</syntaxhighlight>




Another solution could be:
Another solution could be:
<lang lisp>(defun linear-random (seed &key (times 1) (bounds (expt 2 31)) (multiplier 1103515245) (adder 12345) (divisor 1) (max 2147483647) (min 0))
<syntaxhighlight 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)
(loop for candidate = seed then (mod (+ (* multiplier candidate) adder) bounds)
for result = candidate then (floor (/ candidate divisor))
for result = candidate then (floor (/ candidate divisor))
when (and (< result max) (> result min)) collect result into valid-numbers
when (and (< result max) (> result min)) collect result into valid-numbers
when (> (length valid-numbers) times) return result))</lang>
when (> (length valid-numbers) times) return result))</syntaxhighlight>


Which defaults to the BSD formula, but can be customized to any formula with keyword arguments, for example:
Which defaults to the BSD formula, but can be customized to any formula with keyword arguments, for example:
<lang lisp>(format t "Count:~15tBSD:~30tMS:~%~{~{~a~15t~a~30t~a~%~}~}"
<syntaxhighlight lang="lisp">(format t "Count:~15tBSD:~30tMS:~%~{~{~a~15t~a~30t~a~%~}~}"
(loop for i from 0 upto 5 collect
(loop for i from 0 upto 5 collect
(list i
(list i
(linear-random 0 :times i)
(linear-random 0 :times i)
(linear-random 0 :times i :multiplier 214013 :adder 2531011 :max 32767 :divisor (expt 2 16)))))</lang>
(linear-random 0 :times i :multiplier 214013 :adder 2531011 :max 32767 :divisor (expt 2 16)))))</syntaxhighlight>


Outputs:
Outputs:
Line 973: Line 973:


=={{header|D}}==
=={{header|D}}==
<lang d>struct LinearCongruentialGenerator {
<syntaxhighlight lang="d">struct LinearCongruentialGenerator {
enum uint RAND_MAX = (1U << 31) - 1;
enum uint RAND_MAX = (1U << 31) - 1;
uint seed = 0;
uint seed = 0;
Line 1,000: Line 1,000:
foreach (immutable i; 0 .. 10)
foreach (immutable i; 0 .. 10)
writeln(rnd.randMS);
writeln(rnd.randMS);
}</lang>
}</syntaxhighlight>
Output:
Output:
<pre>12345
<pre>12345
Line 1,027: Line 1,027:
''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.
''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(): <lang dc>[*
For BSD rand(): <syntaxhighlight lang="dc">[*
* lrx -- (random number from 0 to 2147483647)
* lrx -- (random number from 0 to 2147483647)
*
*
Line 1,037: Line 1,037:
[* Set seed to 1, then print the first 3 random numbers. *]sz
[* Set seed to 1, then print the first 3 random numbers. *]sz
1 sR
1 sR
lrx psz lrx psz lrx psz</lang>
lrx psz lrx psz lrx psz</syntaxhighlight>


<pre>1103527590
<pre>1103527590
Line 1,043: Line 1,043:
662824084</pre>
662824084</pre>


For Microsoft rand(): <lang dc>[*
For Microsoft rand(): <syntaxhighlight lang="dc">[*
* lrx -- (random number from 0 to 32767)
* lrx -- (random number from 0 to 32767)
*
*
Line 1,053: Line 1,053:
[* Set seed to 1, then print the first 3 random numbers. *]sz
[* Set seed to 1, then print the first 3 random numbers. *]sz
1 sR
1 sR
lrx psz lrx psz lrx psz</lang>
lrx psz lrx psz lrx psz</syntaxhighlight>


<pre>41
<pre>41
Line 1,062: Line 1,062:
{{libheader| Winapi.Windows}}
{{libheader| Winapi.Windows}}
{{Trans|C#}}
{{Trans|C#}}
<syntaxhighlight lang="delphi">
<lang Delphi>
program Linear_congruential_generator;
program Linear_congruential_generator;


Line 1,135: Line 1,135:
end.
end.


</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 1,169: Line 1,169:


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.
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.
<lang edsac>
<syntaxhighlight lang="edsac">
[Linear congruential generators for pseudo-random numbers.
[Linear congruential generators for pseudo-random numbers.
EDSAC program, Initial Orders 2.]
EDSAC program, Initial Orders 2.]
Line 1,298: Line 1,298:
E 15 Z [define entry point]
E 15 Z [define entry point]
P F [acc = 0 on entry]
P F [acc = 0 on entry]
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 1,327: Line 1,327:


=={{header|Elixir}}==
=={{header|Elixir}}==
<lang elixir>defmodule LCG do
<syntaxhighlight lang="elixir">defmodule LCG do
def ms_seed(seed) do
def ms_seed(seed) do
Process.put(:ms_state, seed)
Process.put(:ms_state, seed)
Line 1,361: Line 1,361:
:io.format "~11w~8w~n", [LCG.bsd_rand, LCG.ms_rand]
:io.format "~11w~8w~n", [LCG.bsd_rand, LCG.ms_rand]
end)
end)
end)</lang>
end)</syntaxhighlight>


{{out}}
{{out}}
Line 1,394: Line 1,394:
=={{header|Erlang}}==
=={{header|Erlang}}==
{{trans|Elixir}}
{{trans|Elixir}}
<lang erlang>-module(lcg).
<syntaxhighlight lang="erlang">-module(lcg).
-export([bsd_seed/1, ms_seed/1, bsd_rand/0, ms_rand/0]).
-export([bsd_seed/1, ms_seed/1, bsd_rand/0, ms_rand/0]).


Line 1,414: Line 1,414:
ms_seed(0),
ms_seed(0),
io:fwrite("~10s~c~5s~n", ["BSD", 9, "MS"]),
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)).</lang>
lists:map(fun(_) -> io:fwrite("~10w~c~5w~n", [bsd_rand(),9,ms_rand()]) end, lists:seq(1,10)).</syntaxhighlight>


{{Out}}
{{Out}}
Line 1,431: Line 1,431:
=={{header|ERRE}}==
=={{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).
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).
<lang ERRE>PROGRAM RNG
<syntaxhighlight lang="erre">PROGRAM RNG


!$DOUBLE
!$DOUBLE
Line 1,464: Line 1,464:
PRINT(TAB(10);XRND)
PRINT(TAB(10);XRND)
END FOR
END FOR
END PROGRAM</lang>
END PROGRAM</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,493: Line 1,493:
=={{header|F_Sharp|F#}}==
=={{header|F_Sharp|F#}}==


<lang fsharp>module lcg =
<syntaxhighlight lang="fsharp">module lcg =
let bsd seed =
let bsd seed =
let state = ref seed
let state = ref seed
Line 1,505: Line 1,505:
state := (214013 * !state + 2531011) &&& System.Int32.MaxValue
state := (214013 * !state + 2531011) &&& System.Int32.MaxValue
!state / (1<<<16))
!state / (1<<<16))
</syntaxhighlight>
</lang>
<pre>let rndBSD = lcg.bsd 0;;
<pre>let rndBSD = lcg.bsd 0;;
let BSD=[for n in [0 .. 9] -> rndBSD()];;
let BSD=[for n in [0 .. 9] -> rndBSD()];;
Line 1,520: Line 1,520:
=={{header|Factor}}==
=={{header|Factor}}==
{{works with|Factor|0.98}}
{{works with|Factor|0.98}}
<lang factor>USING: fry io kernel lists lists.lazy math prettyprint ;
<syntaxhighlight lang="factor">USING: fry io kernel lists lists.lazy math prettyprint ;


: lcg ( seed a c m quot: ( state -- rand ) -- list )
: lcg ( seed a c m quot: ( state -- rand ) -- list )
Line 1,527: Line 1,527:
0 1103515245 12345 2147483648 [ ] lcg ! bsd
0 1103515245 12345 2147483648 [ ] lcg ! bsd
0 214013 2531011 2147483648 [ -16 shift ] lcg ! ms
0 214013 2531011 2147483648 [ -16 shift ] lcg ! ms
[ 10 swap ltake [ . ] leach nl ] bi@</lang>
[ 10 swap ltake [ . ] leach nl ] bi@</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,554: Line 1,554:


=={{header|Forth}}==
=={{header|Forth}}==
<lang forth>1 31 lshift 1- constant MAX-RAND-BSD
<syntaxhighlight lang="forth">1 31 lshift 1- constant MAX-RAND-BSD
1 15 lshift 1- constant MAX-RAND-MS
1 15 lshift 1- constant MAX-RAND-MS


Line 1,570: Line 1,570:
;
;


test-random</lang>
test-random</syntaxhighlight>


Output:
Output:
Line 1,589: Line 1,589:
=={{header|Fortran}}==
=={{header|Fortran}}==
{{works with|Fortran|90 and later}}
{{works with|Fortran|90 and later}}
<lang fortran>module lcgs
<syntaxhighlight lang="fortran">module lcgs
implicit none
implicit none


Line 1,630: Line 1,630:
write(*, "(2i12)") bsdrand(), msrand()
write(*, "(2i12)") bsdrand(), msrand()
end do
end do
end program</lang>
end program</syntaxhighlight>
Output
Output
<pre> BSD MS
<pre> BSD MS
Line 1,645: Line 1,645:


=={{header|FreeBASIC}}==
=={{header|FreeBASIC}}==
<lang freebasic>' version 04-11-2016
<syntaxhighlight lang="freebasic">' version 04-11-2016
' compile with: fbc -s console
' compile with: fbc -s console


Line 1,701: Line 1,701:
Print : Print "hit any key to end program"
Print : Print "hit any key to end program"
Sleep
Sleep
End</lang>
End</syntaxhighlight>
{{out}}
{{out}}
<pre>MS generator
<pre>MS generator
Line 1,736: Line 1,736:


=={{header|Go}}==
=={{header|Go}}==
<lang go>package main
<syntaxhighlight lang="go">package main


import "fmt"
import "fmt"
Line 1,770: Line 1,770:
example(0)
example(0)
example(1)
example(1)
}</lang>
}</syntaxhighlight>
Output:
Output:
<pre>
<pre>
Line 1,791: Line 1,791:


=={{header|Haskell}}==
=={{header|Haskell}}==
<lang haskell>bsd = tail . iterate (\n -> (n * 1103515245 + 12345) `mod` 2^31)
<syntaxhighlight 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)
msr = map (`div` 2^16) . tail . iterate (\n -> (214013 * n + 2531011) `mod` 2^31)


main = do
main = do
print $ take 10 $ bsd 0 -- can take seeds other than 0, of course
print $ take 10 $ bsd 0 -- can take seeds other than 0, of course
print $ take 10 $ msr 0</lang>
print $ take 10 $ msr 0</syntaxhighlight>


=={{header|Icon}} and {{header|Unicon}}==
=={{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.
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.
<lang Icon>link printf
<syntaxhighlight lang="icon">link printf


procedure main()
procedure main()
Line 1,824: Line 1,824:
procedure rand_MS() #: lcrng
procedure rand_MS() #: lcrng
return ishift(srand_MS((214013 * srand_MS() + 2531011) % 2147483648),-16)
return ishift(srand_MS((214013 * srand_MS() + 2531011) % 2147483648),-16)
end</lang>
end</syntaxhighlight>


{{libheader|Icon Programming Library}}
{{libheader|Icon Programming Library}}
Line 1,831: Line 1,831:
=={{header|J}}==
=={{header|J}}==
'''Solution:'''
'''Solution:'''
<lang j>lcg=: adverb define
<syntaxhighlight lang="j">lcg=: adverb define
0 m lcg y NB. default seed of 0
0 m lcg y NB. default seed of 0
:
:
Line 1,839: Line 1,839:


rand_bsd=: (1103515245 12345 , <.2^31) lcg
rand_bsd=: (1103515245 12345 , <.2^31) lcg
rand_ms=: (2^16) <.@:%~ (214013 2531011 , <.2^31) lcg</lang>
rand_ms=: (2^16) <.@:%~ (214013 2531011 , <.2^31) lcg</syntaxhighlight>
'''Example Use:'''
'''Example Use:'''
<lang j> rand_bsd 10
<syntaxhighlight lang="j"> rand_bsd 10
12345 1406932606 654583775 1449466924 229283573 1109335178 1051550459 1293799192 794471793 551188310
12345 1406932606 654583775 1449466924 229283573 1109335178 1051550459 1293799192 794471793 551188310
654583775 rand_bsd 4
654583775 rand_bsd 4
Line 1,848: Line 1,848:
38 7719 21238 2437 8855 11797 8365 32285 10450 30612
38 7719 21238 2437 8855 11797 8365 32285 10450 30612
1 rand_ms 5 NB. seed of 1
1 rand_ms 5 NB. seed of 1
41 18467 6334 26500 19169</lang>
41 18467 6334 26500 19169</syntaxhighlight>


=={{header|Java}}==
=={{header|Java}}==
{{works with|Java|8}}
{{works with|Java|8}}
<lang java>import java.util.stream.IntStream;
<syntaxhighlight lang="java">import java.util.stream.IntStream;
import static java.util.stream.IntStream.iterate;
import static java.util.stream.IntStream.iterate;


Line 1,874: Line 1,874:
.map(i -> i >> 16);
.map(i -> i >> 16);
}
}
}</lang>
}</syntaxhighlight>


<pre>BSD:
<pre>BSD:
Line 1,903: Line 1,903:
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.
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.
====Microsoft LCG====
====Microsoft LCG====
<lang jq># 15-bit integers generated using the same formula as rand()
<syntaxhighlight lang="jq"># 15-bit integers generated using the same formula as rand()
# from the Microsoft C Runtime.
# from the Microsoft C Runtime.
# Input: [ count, state, rand ]
# Input: [ count, state, rand ]
Line 1,916: Line 1,916:
| next_rand_Microsoft # the seed is not so random
| next_rand_Microsoft # the seed is not so random
| recurse(if .[0] < n then next_rand_Microsoft else empty end)
| recurse(if .[0] < n then next_rand_Microsoft else empty end)
| .[2];</lang>
| .[2];</syntaxhighlight>
'''Example''':
'''Example''':
rand_Microsoft(1;5)
rand_Microsoft(1;5)
{{out}}
{{out}}
<lang sh>41
<syntaxhighlight lang="sh">41
18467
18467
6334
6334
26500
26500
19169</lang>
19169</syntaxhighlight>
====BSD LCG====
====BSD LCG====
The following code has been tested with the "BigInt" library at [https://gist.github.com/pkoppstein/d06a123f30c033195841].
The following code has been tested with the "BigInt" library at [https://gist.github.com/pkoppstein/d06a123f30c033195841].
<lang jq># BSD rand()
<syntaxhighlight lang="jq"># BSD rand()
# Input: [count, previous]
# Input: [count, previous]
def next_rand_berkeley:
def next_rand_berkeley:
Line 1,940: Line 1,940:
| next_rand_berkeley # skip the seed itself
| next_rand_berkeley # skip the seed itself
| recurse(if .[0] < n then next_rand_berkeley else empty end)
| recurse(if .[0] < n then next_rand_berkeley else empty end)
| .[1];</lang>
| .[1];</syntaxhighlight>
'''Example''':
'''Example''':
rand_berkeley(1;5)
rand_berkeley(1;5)
{{out}}
{{out}}
<lang sh>1103527590
<syntaxhighlight lang="sh">1103527590
377401575
377401575
662824084
662824084
1147902781
1147902781
2035015474</lang>
2035015474</syntaxhighlight>


=={{header|Julia}}==
=={{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.
<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.
<lang julia>using Printf
<syntaxhighlight lang="julia">using Printf


function getlgc(r::Integer, a::Integer, c::Integer, m::Integer, sh::Integer)
function getlgc(r::Integer, a::Integer, c::Integer, m::Integer, sh::Integer)
Line 1,975: Line 1,975:
for _ in 1:nrep
for _ in 1:nrep
@printf("%14d\n", msrand())
@printf("%14d\n", msrand())
end</lang>
end</syntaxhighlight>


{{out}}
{{out}}
Line 2,003: Line 2,003:


=={{header|K}}==
=={{header|K}}==
<lang K> bsd:{1_ y{((1103515245*x)+12345)!(_2^31)}\x}
<syntaxhighlight lang="k"> bsd:{1_ y{((1103515245*x)+12345)!(_2^31)}\x}
ms:{1_(y{_(((214013*x)+2531011)!(_2^31))}\x)%(_2^16)}
ms:{1_(y{_(((214013*x)+2531011)!(_2^31))}\x)%(_2^16)}


Line 2,009: Line 2,009:
12345 1406932606 654583775 1449466924 229283573 1109335178 1051550459 1293799192 794471793 551188310
12345 1406932606 654583775 1449466924 229283573 1109335178 1051550459 1293799192 794471793 551188310
ms[0;10]
ms[0;10]
38 7719 21238 2437 8855 11797 8365 32285 10450 30612</lang>
38 7719 21238 2437 8855 11797 8365 32285 10450 30612</syntaxhighlight>


=={{header|Kotlin}}==
=={{header|Kotlin}}==
<lang scala>// version 1.1.3
<syntaxhighlight lang="scala">// version 1.1.3


class Lcg(val a: Long, val c: Long, val m: Long, val d: Long, val s: Long) {
class Lcg(val a: Long, val c: Long, val m: Long, val d: Long, val s: Long) {
Line 2,030: Line 2,030:
val msc = Lcg(214013, 2531011, 1 shl 31, 1 shl 16, 0)
val msc = Lcg(214013, 2531011, 1 shl 31, 1 shl 16, 0)
for (i in 1..10) println("${msc.nextInt()}")
for (i in 1..10) println("${msc.nextInt()}")
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 2,060: Line 2,060:


=={{header|Liberty BASIC}}==
=={{header|Liberty BASIC}}==
<syntaxhighlight lang="lb">
<lang lb>
'by default these are 0
'by default these are 0
global BSDState
global BSDState
Line 2,084: Line 2,084:
randMS = int(MSState / 2 ^ 16)
randMS = int(MSState / 2 ^ 16)
end function
end function
</syntaxhighlight>
</lang>


=={{header|Logo}}==
=={{header|Logo}}==
Line 2,090: Line 2,090:
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).
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).


<lang Logo>; Configuration parameters for Microsoft and BSD implementations
<syntaxhighlight lang="logo">; Configuration parameters for Microsoft and BSD implementations
make "LCG_MS [214013 2531011 65536 2147483648]
make "LCG_MS [214013 2531011 65536 2147483648]
make "LCG_BSD [1103515245 12345 1 2147483648]
make "LCG_BSD [1103515245 12345 1 2147483648]
Line 2,119: Line 2,119:
print []
print []
]
]
bye</lang>
bye</syntaxhighlight>


Output:<pre>12345
Output:<pre>12345
Line 2,160: Line 2,160:
This requires Lua 5.3 or later because previous versions didn't have support for large integers or integral arithmetic operations.
This requires Lua 5.3 or later because previous versions didn't have support for large integers or integral arithmetic operations.


<lang lua>local RNG = {
<syntaxhighlight lang="lua">local RNG = {
new = function(class, a, c, m, rand)
new = function(class, a, c, m, rand)
local self = setmetatable({}, class)
local self = setmetatable({}, class)
Line 2,186: Line 2,186:
print(("\t%10d"):format(ms.rnd()))
print(("\t%10d"):format(ms.rnd()))
end
end
</syntaxhighlight>
</lang>


{{Out}}
{{Out}}
Line 2,214: Line 2,214:


=={{header|Mathematica}}/{{header|Wolfram Language}}==
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<lang Mathematica>BSDrand[x_] := Mod[x*1103515245 + 12345, 2147483648]
<syntaxhighlight lang="mathematica">BSDrand[x_] := Mod[x*1103515245 + 12345, 2147483648]
NestList[BSDrand, 0, 10]
NestList[BSDrand, 0, 10]
-> {0, 12345, 1406932606, 654583775, 1449466924, 229283573, 1109335178, 1051550459, 1293799192, 794471793, 551188310}
-> {0, 12345, 1406932606, 654583775, 1449466924, 229283573, 1109335178, 1051550459, 1293799192, 794471793, 551188310}
Line 2,220: Line 2,220:
MSrand[x_] := Mod[x*214013 + 2531011, 2147483648]
MSrand[x_] := Mod[x*214013 + 2531011, 2147483648]
BitShiftRight[ NestList[MSrand, 0, 10], 16]
BitShiftRight[ NestList[MSrand, 0, 10], 16]
-> {0, 38, 7719, 21238, 2437, 8855, 11797, 8365, 32285, 10450, 30612}</lang>
-> {0, 38, 7719, 21238, 2437, 8855, 11797, 8365, 32285, 10450, 30612}</syntaxhighlight>


=={{header|Maxima}}==
=={{header|Maxima}}==
<lang maxima>seed: 0$
<syntaxhighlight lang="maxima">seed: 0$
ms_rand() := quotient(seed: mod(214013 * seed + 2531011, 2147483648), 65536)$
ms_rand() := quotient(seed: mod(214013 * seed + 2531011, 2147483648), 65536)$
makelist(ms_rand(), 20); /* see http://oeis.org/A096558 */
makelist(ms_rand(), 20); /* see http://oeis.org/A096558 */
Line 2,236: Line 2,236:
[12345, 1406932606, 654583775, 1449466924, 229283573, 1109335178, 1051550459,
[12345, 1406932606, 654583775, 1449466924, 229283573, 1109335178, 1051550459,
1293799192, 794471793, 551188310, 803550167, 1772930244, 370913197, 639546082, 1381971571,
1293799192, 794471793, 551188310, 803550167, 1772930244, 370913197, 639546082, 1381971571,
1695770928, 2121308585, 1719212846, 996984527, 1157490780]</lang>
1695770928, 2121308585, 1719212846, 996984527, 1157490780]</syntaxhighlight>


=={{header|Nim}}==
=={{header|Nim}}==
<lang nim>proc bsdRand(seed: int): iterator: int =
<syntaxhighlight lang="nim">proc bsdRand(seed: int): iterator: int =
var state = seed
var state = seed
result = iterator: int =
result = iterator: int =
Line 2,270: Line 2,270:
inc count
inc count
if count == 10:
if count == 10:
break</lang>
break</syntaxhighlight>


{{out}}
{{out}}
Line 2,301: Line 2,301:
Function genLCG returns a block object that, when performed, will return the next random number from the LCG.
Function genLCG returns a block object that, when performed, will return the next random number from the LCG.


<lang Oforth>: genLCG(a, c, m, seed)
<syntaxhighlight lang="oforth">: genLCG(a, c, m, seed)
| ch |
| ch |
Channel newSize(1) dup send(seed) drop ->ch
Channel newSize(1) dup send(seed) drop ->ch
#[ ch receive a * c + m mod dup ch send drop ] ;</lang>
#[ ch receive a * c + m mod dup ch send drop ] ;</syntaxhighlight>


{{out}}
{{out}}
Line 2,335: Line 2,335:
=={{header|PARI/GP}}==
=={{header|PARI/GP}}==
Note that up to PARI/GP version 2.4.0, <code>random()</code> used a linear congruential generator.
Note that up to PARI/GP version 2.4.0, <code>random()</code> used a linear congruential generator.
<lang parigp>BSDseed=Mod(1,1<<31);
<syntaxhighlight lang="parigp">BSDseed=Mod(1,1<<31);
MSFTseed=Mod(1,1<<31);
MSFTseed=Mod(1,1<<31);
BSD()=BSDseed=1103515245*BSDseed+12345;lift(BSDseed);
BSD()=BSDseed=1103515245*BSDseed+12345;lift(BSDseed);
MSFT()=MSFTseed=214013*MSFTseed+2531011;lift(MSFTseed)%(1<<31);</lang>
MSFT()=MSFTseed=214013*MSFTseed+2531011;lift(MSFTseed)%(1<<31);</syntaxhighlight>


=={{header|Pascal}}==
=={{header|Pascal}}==
<lang pascal>Program LinearCongruentialGenerator(output);
<syntaxhighlight lang="pascal">Program LinearCongruentialGenerator(output);
{$mode iso}
{$mode iso}
var
var
Line 2,375: Line 2,375:
writeln(bsdrand:12, msrand:12);
writeln(bsdrand:12, msrand:12);
end.
end.
</syntaxhighlight>
</lang>
Output:
Output:
<pre> BSD MS
<pre> BSD MS
Line 2,390: Line 2,390:


=={{header|Perl}}==
=={{header|Perl}}==
Creates a magic scalar whose value is next in the LCG sequence when read.<lang perl>use strict;
Creates a magic scalar whose value is next in the LCG sequence when read.<syntaxhighlight lang="perl">use strict;
package LCG;
package LCG;


Line 2,429: Line 2,429:


print "\nMS:\n";
print "\nMS:\n";
print "$rand\n" for 1 .. 10;</lang>output<lang>BSD:
print "$rand\n" for 1 .. 10;</syntaxhighlight>output<syntaxhighlight lang="text">BSD:
12345
12345
1406932606
1406932606
Line 2,451: Line 2,451:
32285
32285
10450
10450
30612</lang>
30612</syntaxhighlight>


=={{header|Phix}}==
=={{header|Phix}}==
{{libheader|Phix/mpfr}}
{{libheader|Phix/mpfr}}
As per the comments, I had to resort to gmp 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>(phixonline)-->
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<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: #004080;">atom</span> <span style="color: #000000;">seed</span>
Line 2,490: Line 2,490:
<span style="color: #0000FF;">?</span><span style="color: #008000;">"MSrnd"</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>
<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>
<!--</lang>-->
<!--</syntaxhighlight>-->
{{out}}
{{out}}
<pre>
<pre>
Line 2,519: Line 2,519:
=={{header|PHP}}==
=={{header|PHP}}==
{{works with|PHP|5.3+}}
{{works with|PHP|5.3+}}
<lang php><?php
<syntaxhighlight lang="php"><?php
function bsd_rand($seed) {
function bsd_rand($seed) {
return function() use (&$seed) {
return function() use (&$seed) {
Line 2,543: Line 2,543:
echo $lcg(), " ";
echo $lcg(), " ";
echo "\n";
echo "\n";
?></lang>
?></syntaxhighlight>


=={{header|Picat}}==
=={{header|Picat}}==
===Methods as hard coded predicates===
===Methods as hard coded predicates===
<lang Picat>go =>
<syntaxhighlight lang="picat">go =>


% BSD
% BSD
Line 2,577: Line 2,577:
Seed = cond(M.has_key(ms_state),M.get(ms_state),0),
Seed = cond(M.has_key(ms_state),M.get(ms_state),0),
Rand = ((214013*Seed + 2531011) mod 2**31),
Rand = ((214013*Seed + 2531011) mod 2**31),
M.put(ms_state,Rand).</lang>
M.put(ms_state,Rand).</syntaxhighlight>


{{out}}
{{out}}
Line 2,587: Line 2,587:
===Generalized version===
===Generalized version===
Using a global global map for setting/setting seeds etc.
Using a global global map for setting/setting seeds etc.
<lang Picat>go2 =>
<syntaxhighlight lang="picat">go2 =>


% BSD
% BSD
Line 2,623: Line 2,623:
Rand = ((M.get(multiplier)*M.get(seed) + M.get(adder)) mod M.get(mod)),
Rand = ((M.get(multiplier)*M.get(seed) + M.get(adder)) mod M.get(mod)),
M.put(seed,Rand),
M.put(seed,Rand),
get_global_map().put(Type,M).</lang>
get_global_map().put(Type,M).</syntaxhighlight>


{{out}}
{{out}}
Line 2,633: Line 2,633:


=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
<lang PicoLisp>(zero *BsdSeed *MsSeed)
<syntaxhighlight lang="picolisp">(zero *BsdSeed *MsSeed)


(de bsdRand ()
(de bsdRand ()
Line 2,642: Line 2,642:
(>> 16
(>> 16
(setq *MsSeed
(setq *MsSeed
(& (+ 2531011 (* 214013 *MsSeed)) `(dec (** 2 31))) ) ) )</lang>
(& (+ 2531011 (* 214013 *MsSeed)) `(dec (** 2 31))) ) ) )</syntaxhighlight>
Output:
Output:
<pre>: (do 7 (printsp (bsdRand)))
<pre>: (do 7 (printsp (bsdRand)))
Line 2,651: Line 2,651:


=={{header|PL/I}}==
=={{header|PL/I}}==
<lang>
<syntaxhighlight lang="text">
(nofixedoverflow, nosize):
(nofixedoverflow, nosize):
LCG: procedure options (main);
LCG: procedure options (main);
Line 2,680: Line 2,680:


end LCG;
end LCG;
</syntaxhighlight>
</lang>
OUTPUT:
OUTPUT:
<pre>
<pre>
Line 2,707: Line 2,707:


=={{header|PowerShell}}==
=={{header|PowerShell}}==
<lang powershell>
<syntaxhighlight lang="powershell">
Function msstate{
Function msstate{
Param($current_seed)
Param($current_seed)
Line 2,732: Line 2,732:
$seed = randBSD($seed)
$seed = randBSD($seed)
Write-Host $seed}
Write-Host $seed}
</syntaxhighlight>
</lang>


{{Out}}
{{Out}}
Line 2,751: Line 2,751:


=={{header|PureBasic}}==
=={{header|PureBasic}}==
<lang purebasic>Procedure ms_LCG(seed.q = -1)
<syntaxhighlight lang="purebasic">Procedure ms_LCG(seed.q = -1)
Static state.q
Static state.q
If seed >= 0
If seed >= 0
Line 2,787: Line 2,787:
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
CloseConsole()
CloseConsole()
EndIf</lang>
EndIf</syntaxhighlight>
Sample output:
Sample output:
<pre>BSD (seed = 1)
<pre>BSD (seed = 1)
Line 2,804: Line 2,804:


=={{header|Python}}==
=={{header|Python}}==
<lang python>def bsd_rand(seed):
<syntaxhighlight lang="python">def bsd_rand(seed):
def rand():
def rand():
rand.seed = (1103515245*rand.seed + 12345) & 0x7fffffff
rand.seed = (1103515245*rand.seed + 12345) & 0x7fffffff
Line 2,816: Line 2,816:
return rand.seed >> 16
return rand.seed >> 16
rand.seed = seed
rand.seed = seed
return rand</lang>
return rand</syntaxhighlight>
{{works with|Python|3.x}}
{{works with|Python|3.x}}
<lang python>def bsd_rand(seed):
<syntaxhighlight lang="python">def bsd_rand(seed):
def rand():
def rand():
nonlocal seed
nonlocal seed
Line 2,830: Line 2,830:
seed = (214013*seed + 2531011) & 0x7fffffff
seed = (214013*seed + 2531011) & 0x7fffffff
return seed >> 16
return seed >> 16
return rand</lang>
return rand</syntaxhighlight>


=={{header|Quackery}}==
=={{header|Quackery}}==


<lang Quackery> [ number$
<syntaxhighlight lang="quackery"> [ number$
10 over size -
10 over size -
space swap of
space swap of
Line 2,859: Line 2,859:
10 times
10 times
[ BSD-rand echonum
[ BSD-rand echonum
MCR-rand echonum cr ]</lang>
MCR-rand echonum cr ]</syntaxhighlight>


{{out}}
{{out}}
Line 2,877: Line 2,877:


=={{header|R}}==
=={{header|R}}==
<lang r>library(gmp) # for big integers
<syntaxhighlight lang="r">library(gmp) # for big integers


rand_BSD <- function(n = 1) {
rand_BSD <- function(n = 1) {
Line 2,914: Line 2,914:
seed <- 0
seed <- 0
rand_MS(10)
rand_MS(10)
## [1] 38 7719 21238 2437 8855 11797 8365 32285 10450 30612</lang>
## [1] 38 7719 21238 2437 8855 11797 8365 32285 10450 30612</syntaxhighlight>


=={{header|Racket}}==
=={{header|Racket}}==
Line 2,920: Line 2,920:
The following solution uses generators and transcribes the mathematical formulas above directly. It does not attempt to be efficient.
The following solution uses generators and transcribes the mathematical formulas above directly. It does not attempt to be efficient.


<lang racket>
<syntaxhighlight lang="racket">
#lang racket
#lang racket
(require racket/generator)
(require racket/generator)
Line 2,941: Line 2,941:
(define bsd-rand (rand bsd-update identity))
(define bsd-rand (rand bsd-update identity))
(define ms-rand (rand ms-update (λ (x) (quotient x (expt 2 16)))))
(define ms-rand (rand ms-update (λ (x) (quotient x (expt 2 16)))))
</syntaxhighlight>
</lang>


=={{header|Raku}}==
=={{header|Raku}}==
Line 2,948: Line 2,948:
We'll define subroutines implementing the LCG algorithm for each version. We'll make them return a lazy list.
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;
<syntaxhighlight lang="raku" line>constant modulus = 2**31;
sub bsd {
sub bsd {
$^seed, ( 1103515245 * * + 12345 ) % modulus ... *
$^seed, ( 1103515245 * * + 12345 ) % modulus ... *
Line 2,962: Line 2,962:
say "\nMS LCG first 10 values (first one is the seed):";
say "\nMS LCG first 10 values (first one is the seed):";
.say for ms(0)[^10];</lang>
.say for ms(0)[^10];</syntaxhighlight>


<pre>BSD LCG first 10 values (first one is the seed):
<pre>BSD LCG first 10 values (first one is the seed):
Line 2,989: Line 2,989:


=={{header|REXX}}==
=={{header|REXX}}==
<lang rexx>/*REXX program uses a linear congruential generator (LCG) that simulates the old BSD */
<syntaxhighlight lang="rexx">/*REXX program uses a linear congruential generator (LCG) that simulates the old BSD */
/*──────── and MS random number generators: BSD= 0──►(2^31)-1 MS= 0──►(2^16)-1 */
/*──────── and MS random number generators: BSD= 0──►(2^31)-1 MS= 0──►(2^16)-1 */
numeric digits 20 /*use enough dec. digs for the multiply*/
numeric digits 20 /*use enough dec. digs for the multiply*/
Line 3,010: Line 3,010:
" rand" right(ms % two@@16, 6)
" rand" right(ms % two@@16, 6)
end /*j*/
end /*j*/
end /*seed*/ /*stick a fork in it, we're all done. */</lang>
end /*seed*/ /*stick a fork in it, we're all done. */</syntaxhighlight>
{{out|output|text= &nbsp; &nbsp; (shown at five-sixth size.) }}
{{out|output|text= &nbsp; &nbsp; (shown at five-sixth size.) }}
<pre style="font-size:84%">
<pre style="font-size:84%">
Line 3,060: Line 3,060:
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.
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.


<lang ruby>module LCG
<syntaxhighlight lang="ruby">module LCG
module Common
module Common
# The original seed of this generator.
# The original seed of this generator.
Line 3,089: Line 3,089:
end
end
end
end
end</lang>
end</syntaxhighlight>


The next example sets the seed to 1, and prints the first 5 random numbers.
The next example sets the seed to 1, and prints the first 5 random numbers.


<lang ruby>lcg = LCG::Berkeley.new(1)
<syntaxhighlight lang="ruby">lcg = LCG::Berkeley.new(1)
p (1..5).map {lcg.rand}
p (1..5).map {lcg.rand}
# prints [1103527590, 377401575, 662824084, 1147902781, 2035015474]
# prints [1103527590, 377401575, 662824084, 1147902781, 2035015474]
Line 3,099: Line 3,099:
lcg = LCG::Microsoft.new(1)
lcg = LCG::Microsoft.new(1)
p (1..5).map {lcg.rand}
p (1..5).map {lcg.rand}
# prints [41, 18467, 6334, 26500, 19169]</lang>
# prints [41, 18467, 6334, 26500, 19169]</syntaxhighlight>


=={{header|Run BASIC}}==
=={{header|Run BASIC}}==
<lang runbasic>global bsd
<syntaxhighlight lang="runbasic">global bsd
global ms
global ms
print "Num ___Bsd___";chr$(9);"__Ms_"
print "Num ___Bsd___";chr$(9);"__Ms_"
Line 3,117: Line 3,117:
ms = (214013 * ms + 2531011) mod (2 ^ 31)
ms = (214013 * ms + 2531011) mod (2 ^ 31)
msRnd = int(ms / 2 ^ 16)
msRnd = int(ms / 2 ^ 16)
end function</lang>
end function</syntaxhighlight>
<pre>
<pre>
Num ___Bsd___ __Ms_
Num ___Bsd___ __Ms_
Line 3,132: Line 3,132:


=={{header|Rust}}==
=={{header|Rust}}==
<lang rust>extern crate rand;
<syntaxhighlight lang="rust">extern crate rand;


pub use rand::{Rng, SeedableRng};
pub use rand::{Rng, SeedableRng};
Line 3,202: Line 3,202:
println!("{}", ms.gen::<bool>());
println!("{}", ms.gen::<bool>());
println!("{}", ms.gen_ascii_chars().take(15).collect::<String>());
println!("{}", ms.gen_ascii_chars().take(15).collect::<String>());
}</lang>
}</syntaxhighlight>


=={{header|Scala}}==
=={{header|Scala}}==
<lang scala>object LinearCongruentialGenerator {
<syntaxhighlight lang="scala">object LinearCongruentialGenerator {
def bsdRandom(rseed:Int):Iterator[Int]=new Iterator[Int]{
def bsdRandom(rseed:Int):Iterator[Int]=new Iterator[Int]{
var seed=rseed
var seed=rseed
Line 3,229: Line 3,229:
println("MS : "+ toString( msRandom(1)))
println("MS : "+ toString( msRandom(1)))
}
}
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>-- seed 0 --
<pre>-- seed 0 --
Line 3,250: Line 3,250:
{{incomplete|Scheme|Precise which Scheme implementation and version you are using and which Report on the Algorithmic Language
{{incomplete|Scheme|Precise which Scheme implementation and version you are using and which Report on the Algorithmic Language
Scheme version it supports}}
Scheme version it supports}}
<lang scheme>(define ((bsd-rand seed)) (set! seed (remainder (+ (* 1103515245 seed) 12345) 2147483648)) seed)
<syntaxhighlight lang="scheme">(define ((bsd-rand seed)) (set! seed (remainder (+ (* 1103515245 seed) 12345) 2147483648)) seed)


(define ((msvcrt-rand seed)) (set! seed (remainder (+ (* 214013 seed) 2531011) 2147483648)) (quotient seed 65536))
(define ((msvcrt-rand seed)) (set! seed (remainder (+ (* 214013 seed) 2531011) 2147483648)) (quotient seed 65536))
Line 3,261: Line 3,261:


(rand-list (msvcrt-rand 0) 10)
(rand-list (msvcrt-rand 0) 10)
; (38 7719 21238 2437 8855 11797 8365 32285 10450 30612)</lang>
; (38 7719 21238 2437 8855 11797 8365 32285 10450 30612)</syntaxhighlight>


=={{header|Seed7}}==
=={{header|Seed7}}==
Line 3,271: Line 3,271:
[http://seed7.sourceforge.net/libraries/array.htm#rand%28in_arrayType%29 rand(arr)]. This function selects a random element from an array.
[http://seed7.sourceforge.net/libraries/array.htm#rand%28in_arrayType%29 rand(arr)]. This function selects a random element from an array.


<lang seed7>$ include "seed7_05.s7i";
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i";
include "bigint.s7i";
include "bigint.s7i";


Line 3,301: Line 3,301:
writeln(bsdRand lpad 12 <& msRand lpad 12);
writeln(bsdRand lpad 12 <& msRand lpad 12);
end for;
end for;
end func;</lang>
end func;</syntaxhighlight>


Output:
Output:
Line 3,321: Line 3,321:
Uses the Random library provided by SequenceL to create new Random Number Generators
Uses the Random library provided by SequenceL to create new Random Number Generators


<syntaxhighlight lang="sequencel">
<lang sequenceL>
import <Utilities/Random.sl>;
import <Utilities/Random.sl>;


Line 3,348: Line 3,348:
(Value : newSeed / 65536,
(Value : newSeed / 65536,
Generator : (Seed : newSeed, RandomMin : RG.RandomMin, RandomMax : RG.RandomMax, NextFunction : RG.NextFunction));
Generator : (Seed : newSeed, RandomMin : RG.RandomMin, RandomMax : RG.RandomMax, NextFunction : RG.NextFunction));
</syntaxhighlight>
</lang>
Output
Output
<pre>
<pre>
Line 3,357: Line 3,357:
=={{header|Sidef}}==
=={{header|Sidef}}==
{{trans|Ruby}}
{{trans|Ruby}}
<lang ruby>module LCG {
<syntaxhighlight lang="ruby">module LCG {


# Creates a linear congruential generator and remembers the initial seed.
# Creates a linear congruential generator and remembers the initial seed.
Line 3,386: Line 3,386:


var lcg2 = LCG::Microsoft(1)
var lcg2 = LCG::Microsoft(1)
say 5.of { lcg2.rand }</lang>
say 5.of { lcg2.rand }</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 3,394: Line 3,394:


=={{header|Sparkling}}==
=={{header|Sparkling}}==
<lang sparkling>var states = {
<syntaxhighlight lang="sparkling">var states = {
"BSD": 0,
"BSD": 0,
"MS": 0
"MS": 0
Line 3,413: Line 3,413:
function Microsoft_rand() {
function Microsoft_rand() {
return (states.MS = (214013 * states.MS + 2531011) % (1 << 31)) % (1 << 15);
return (states.MS = (214013 * states.MS + 2531011) % (1 << 31)) % (1 << 15);
}</lang>
}</syntaxhighlight>


Output seen after seeding both generators with 0:
Output seen after seeding both generators with 0:


<lang sparkling>spn:8> Microsoft_seed(0);
<syntaxhighlight lang="sparkling">spn:8> Microsoft_seed(0);
spn:9> Microsoft_rand()
spn:9> Microsoft_rand()
= 7875
= 7875
Line 3,438: Line 3,438:
= 1449466924
= 1449466924
spn:19> BSD_rand()
spn:19> BSD_rand()
= 229283573</lang>
= 229283573</syntaxhighlight>


=={{header|Standard ML}}==
=={{header|Standard ML}}==
<lang sml>local
<syntaxhighlight lang="sml">local
open Word32
open Word32
in
in
Line 3,452: Line 3,452:
(toInt (>> (state, 0w16)), state)
(toInt (>> (state, 0w16)), state)
end
end
end</lang>
end</syntaxhighlight>
;Test code<nowiki>:</nowiki>
;Test code<nowiki>:</nowiki>
<lang sml>fun test1 rand =
<syntaxhighlight lang="sml">fun test1 rand =
(print (" " ^ Int.toString rand); rand)
(print (" " ^ Int.toString rand); rand)


Line 3,467: Line 3,467:
val () = print "\nMSC:\n"
val () = print "\nMSC:\n"
val () = doTimes (test2 o mscLcg, 7, 0w0)
val () = doTimes (test2 o mscLcg, 7, 0w0)
val () = print "\n"</lang>
val () = print "\n"</syntaxhighlight>
{{out}}
{{out}}
<pre>BSD:
<pre>BSD:
Line 3,476: Line 3,476:
=={{header|Stata}}==
=={{header|Stata}}==


<lang stata>mata
<syntaxhighlight lang="stata">mata
function rand_bsd(u) {
function rand_bsd(u) {
m = 65536
m = 65536
Line 3,500: Line 3,500:


rand_seq(&rand_bsd(),1,10)
rand_seq(&rand_bsd(),1,10)
rand_seq(&rand_ms(),0,10)</lang>
rand_seq(&rand_ms(),0,10)</syntaxhighlight>


'''Output''': compare with OEIS '''[http://oeis.org/A096553 A096553]''' and '''[http://oeis.org/A096558 A096558]'''.
'''Output''': compare with OEIS '''[http://oeis.org/A096553 A096553]''' and '''[http://oeis.org/A096558 A096558]'''.
Line 3,535: Line 3,535:
=={{header|Swift}}==
=={{header|Swift}}==


<lang Swift>import Cocoa
<syntaxhighlight lang="swift">import Cocoa


class LinearCongruntialGenerator {
class LinearCongruntialGenerator {
Line 3,581: Line 3,581:
{
{
print(BSDLinearCongruntialGenerator.random())
print(BSDLinearCongruntialGenerator.random())
}</lang>
}</syntaxhighlight>
{{out}}<pre>Microsft Rand:
{{out}}<pre>Microsft Rand:
38
38
Line 3,608: Line 3,608:
=={{header|Tcl}}==
=={{header|Tcl}}==
Using an object-oriented solution, inspired by (but not a translation of) the [[#Ruby|Ruby]] solution above.
Using an object-oriented solution, inspired by (but not a translation of) the [[#Ruby|Ruby]] solution above.
<lang tcl>package require Tcl 8.6
<syntaxhighlight lang="tcl">package require Tcl 8.6


# General form of a linear-congruential RNG
# General form of a linear-congruential RNG
Line 3,637: Line 3,637:
next $initialSeed 214013 2531011 [expr {2**31}] [expr {2**16}]
next $initialSeed 214013 2531011 [expr {2**31}] [expr {2**16}]
}
}
}</lang>
}</syntaxhighlight>
Demo code:
Demo code:
<lang tcl>proc sample rng {foreach - {1 2 3 4 5} {lappend r [$rng rand]}; join $r ", "}
<syntaxhighlight 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 BSD:\t\[[sample [BSDRNG new 1]]\]
puts MS:\t\[[sample [MSRNG new 1]]\]</lang>
puts MS:\t\[[sample [MSRNG new 1]]\]</syntaxhighlight>
Output:
Output:
<pre>
<pre>
Line 3,650: Line 3,650:
=={{header|uBasic/4tH}}==
=={{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.
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.
<lang>w = 32 ' Change for different integer size
<syntaxhighlight lang="text">w = 32 ' Change for different integer size
b = 0 ' Initial BSD seed
b = 0 ' Initial BSD seed
m = 0 ' Initial MS seed
m = 0 ' Initial MS seed
Line 3,684: Line 3,684:
m = Pop() % (2 ^ 31) ' Now we got a number less than 2^31
m = Pop() % (2 ^ 31) ' Now we got a number less than 2^31
Push m / (2 ^ 16) ' So we can complete the operation
Push m / (2 ^ 16) ' So we can complete the operation
Return</lang>
Return</syntaxhighlight>
{{out}}
{{out}}
<pre>BSD
<pre>BSD
Line 3,715: Line 3,715:
=={{header|UNIX Shell}}==
=={{header|UNIX Shell}}==


<lang bash>#! /bin/bash
<syntaxhighlight lang="bash">#! /bin/bash


function BSD() {
function BSD() {
Line 3,739: Line 3,739:


output BSD
output BSD
output MS</lang>
output MS</syntaxhighlight>


{{out}}
{{out}}
Line 3,770: Line 3,770:


=={{header|VBA}}==
=={{header|VBA}}==
<lang vb>Public stateBSD As Variant
<syntaxhighlight lang="vb">Public stateBSD As Variant
Public stateMS As Variant
Public stateMS As Variant
Private Function bsd() As Long
Private Function bsd() As Long
Line 3,795: Line 3,795:
Debug.Print Format(bsd, "@@@@@@@@@@"), Format(ms, "@@@@@")
Debug.Print Format(bsd, "@@@@@@@@@@"), Format(ms, "@@@@@")
Next i
Next i
End Sub</lang>{{out}}
End Sub</syntaxhighlight>{{out}}
<pre> BSD MS
<pre> BSD MS
12345 38
12345 38
Line 3,813: Line 3,813:
{{libheader|Wren-fmt}}
{{libheader|Wren-fmt}}
Some of the intermediate calculations here require integers >= 2^53 so we need to use BigInt.
Some of the intermediate calculations here require integers >= 2^53 so we need to use BigInt.
<lang ecmascript>import "/big" for BigInt
<syntaxhighlight lang="ecmascript">import "/big" for BigInt
import "/fmt" for Fmt
import "/fmt" for Fmt


Line 3,842: Line 3,842:


example.call(0)
example.call(0)
example.call(1)</lang>
example.call(1)</syntaxhighlight>


{{out}}
{{out}}
Line 3,868: Line 3,868:


First example using integer instructions.
First example using integer instructions.
<lang asm>;x86-64 assembly code for Microsoft Windows
<syntaxhighlight lang="asm">;x86-64 assembly code for Microsoft Windows
;Tested in windows 7 Enterprise Service Pack 1 64 bit
;Tested in windows 7 Enterprise Service Pack 1 64 bit
;With the AMD FX(tm)-6300 processor
;With the AMD FX(tm)-6300 processor
Line 4,055: Line 4,055:


mov rcx,1
mov rcx,1
call exit</lang>
call exit</syntaxhighlight>


Second example using AVX instructions.
Second example using AVX instructions.
{{incorrect|X86 Assembly|It will not produce output identical to that of the Microsoft rand() function.}}
{{incorrect|X86 Assembly|It will not produce output identical to that of the Microsoft rand() function.}}
<lang asm>;x86-64 assembly code for Microsoft Windows
<syntaxhighlight lang="asm">;x86-64 assembly code for Microsoft Windows
;Tested in windows 7 Enterprise Service Pack 1 64 bit
;Tested in windows 7 Enterprise Service Pack 1 64 bit
;With the AMD FX(tm)-6300 processor
;With the AMD FX(tm)-6300 processor
Line 4,302: Line 4,302:


mov rcx,1
mov rcx,1
call exit</lang>
call exit</syntaxhighlight>


{{out|Sample}}
{{out|Sample}}
Line 4,364: Line 4,364:
[[File:LCG2XPL0.gif|right]]
[[File:LCG2XPL0.gif|right]]


<lang XPL0>include c:\cxpl\codes;
<syntaxhighlight lang="xpl0">include c:\cxpl\codes;
int R;
int R;


Line 4,392: Line 4,392:
N:= ChIn(1); \wait for keystoke
N:= ChIn(1); \wait for keystoke
SetVid(3); \restore normal text mode
SetVid(3); \restore normal text mode
]</lang>
]</syntaxhighlight>


=={{header|zkl}}==
=={{header|zkl}}==
<lang zkl>var [private] seed = 0;
<syntaxhighlight lang="zkl">var [private] seed = 0;
fcn srand(s){ seed = s }
fcn srand(s){ seed = s }


Line 4,408: Line 4,408:
const A=214013, C=2531011, TWO16=(1).shiftLeft(16);
const A=214013, C=2531011, TWO16=(1).shiftLeft(16);
fcn rand{ (seed = (seed * A + C) % TWO31) / TWO16 }
fcn rand{ (seed = (seed * A + C) % TWO31) / TWO16 }
#endif</lang>
#endif</syntaxhighlight>
<lang zkl>srand(0);
<syntaxhighlight lang="zkl">srand(0);
println(rand(),",",rand(),",",rand());</lang>
println(rand(),",",rand(),",",rand());</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>