Linear congruential generator: Difference between revisions

Added Easylang
(Added Easylang)
 
(21 intermediate revisions by 15 users not shown)
Line 37:
More info is at [[Random number generator (included)#C]].
<br><br>
 
=={{header|11l}}==
<syntaxhighlight lang="11l">T LinearCongruentialGenerator
seed = 0
Int a, c, m
 
F (a, c, m)
.a = a
.c = c
.m = m
 
F ()()
.seed = (.a * .seed + .c) [&] .m
R .seed
 
V bsd_rnd = LinearCongruentialGenerator(1103515245, 12345, 7FFF'FFFF)
V ms_rnd = LinearCongruentialGenerator(214013, 2531011, 7FFF'FFFF)
 
print(‘BSD RAND:’)
L 5
print(bsd_rnd())
print()
print(‘MS RAND:’)
L 5
print(ms_rnd() >> 16)</syntaxhighlight>
 
{{out}}
<pre>
BSD RAND:
12345
1406932606
654583775
1449466924
229283573
 
MS RAND:
38
7719
21238
2437
8855
</pre>
 
=={{header|360 Assembly}}==
<langsyntaxhighlight lang="360asm">* Linear congruential generator 07/03/2017
LINCONG CSECT
USING LINCONG,R12
Line 76 ⟶ 118:
XDEC DS CL12
YREGS
END LINCONG</langsyntaxhighlight>
{{out}}
<pre>
Line 95 ⟶ 137:
We first specify a generic package LCG:
 
<langsyntaxhighlight Adalang="ada">generic
type Base_Type is mod <>;
Multiplyer, Adder: Base_Type;
Line 105 ⟶ 147:
-- changes the state and outputs the result
 
end LCG;</langsyntaxhighlight>
 
Then we provide a generic implementation:
 
<langsyntaxhighlight Adalang="ada">package body LCG is
 
State: Base_Type := Base_Type'First;
Line 124 ⟶ 166:
end Random;
 
end LCG;</langsyntaxhighlight>
 
Next, we define the MS- and BSD-instantiations of the generic package:
 
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO, LCG;
 
procedure Run_LCGs is
Line 147 ⟶ 189:
Ada.Text_IO.Put_Line(M31'Image(MS_Rand.Random));
end loop;
end Run_LCGs;</langsyntaxhighlight>
 
Finally, we run the program, which generates the following output (note that the first ten lines are from the BSD generator, the next ten from the MS generator):
Line 173 ⟶ 215:
 
=={{header|ALGOL 68}}==
<langsyntaxhighlight lang="algol68">
BEGIN
COMMENT
Line 253 ⟶ 295:
srand (0)
END
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 280 ⟶ 322:
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight AutoHotkeylang="autohotkey">a := 0, b:= [0]
Loop, 10
BSD .= "`t" (a := BSD(a)) "`n"
Line 295 ⟶ 337:
Seed := Mod(214013 * Seed + 2531011, 2147483648)
return, [Seed, Seed // 65536]
}</langsyntaxhighlight>
'''Output:'''
<pre>BSD:
Line 321 ⟶ 363:
30612</pre>
 
=={{header|Batch File}}==
<syntaxhighlight lang="dos">@echo off & setlocal enabledelayedexpansion
<lang batch>
@echo off & setlocal enabledelayedexpansion
 
echo BSD Rand
Line 346 ⟶ 387:
set p2= %2
echo %p1:~-2% %p2:~-10%
goto:eof</syntaxhighlight>
</lang>
'''Output:'''
<pre>
Line 377 ⟶ 416:
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<langsyntaxhighlight lang="bbcbasic"> @% = &D0D
PRINT "MS generator:"
dummy% = FNrandMS(0)
Line 410 ⟶ 449:
DEF FNmuladd(A%,B%,C%) : PRIVATE M% : LOCAL P% : IF M% = 0 DIM P% 8
IF P% THEN [OPT 0 : .M% mul ebx : add eax,ecx : btr eax,31 : ret :]
= USR M%</langsyntaxhighlight>
'''Output:'''
<pre>
Line 444 ⟶ 483:
 
As with dc, bc has no bitwise operators.
<langsyntaxhighlight lang="bc">/* BSD rand */
 
define rand() {
Line 462 ⟶ 501:
 
randseed = 1
rand(); rand(); rand(); print "\n"</langsyntaxhighlight>
 
=={{header|Befunge}}==
This required a bit of trickery to handle signed overflow and negative division in a portable way. It still won't work on all implementations, though. In particular Javascript-based interpreters can't handle the BSD formula because of the way Javascript numbers lose their least significant digits when they become too large.
 
<langsyntaxhighlight lang="befunge">>025*>\::0\`288*::*:****+.55+,"iQ"5982156*:v
v $$_^#!\-1:\%***:*::*882 ++*"yf"3***+***+*<
>025*>\:488**:*/:0\`6"~7"+:*+01-2/-*+."O?+"55v
@ $$_^#!\-1:\%***:*::*882 ++***" ''4C"*+2**,+<</langsyntaxhighlight>
 
{{out}}
Line 497 ⟶ 536:
 
=={{header|Bracmat}}==
<langsyntaxhighlight lang="bracmat">( 2^31:?RANDMAX
& 2^-16:?rshift
& (randBSD=mod$(!seed*1103515245+12345.!RANDMAX):?seed)
Line 512 ⟶ 551:
& 0:?i
& whl'(1+!i:~>10:?i&out$!randMS)
)</langsyntaxhighlight>
 
Output:
Line 541 ⟶ 580:
=={{header|C}}==
In a pretended lib style, this code produces a rand() function depends on compiler macro: <code>gcc -DMS_RAND</code> uses MS style, otherwise it's BSD rand by default.
<langsyntaxhighlight Clang="c">#include <stdio.h>
 
/* always assuming int is at least 32 bits */
Line 581 ⟶ 620:
 
return 0;
}</langsyntaxhighlight>
 
=={{header|C sharp|C#}}==
{{works with|C sharp|C#|6+}}
<!-- By Martin Freedman, 17/01/2018 -->
<langsyntaxhighlight Csharplang="csharp">using System;
using System.Collections.Generic;
using System.Linq;
Line 621 ⟶ 660:
}
}
}</langsyntaxhighlight>
Produces:
<pre>BSD next 10 Random
Line 647 ⟶ 686:
</pre>
From a Free Cell Deal solution
<syntaxhighlight lang="csharp">
<lang Csharp>
using System;
using System.Collections.Generic;
Line 715 ⟶ 754:
}
}
</syntaxhighlight>
</lang>
Output:
<pre>Microsoft
Line 743 ⟶ 782:
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">#include <iostream>
 
//--------------------------------------------------------------------------------------------------
Line 793 ⟶ 832:
return 0;
}
//--------------------------------------------------------------------------------------------------</langsyntaxhighlight>
Output:
<pre>
Line 825 ⟶ 864:
; C++11
{{works with|C++11}}
<langsyntaxhighlight lang="cpp">#include <iostream>
#include <random>
 
Line 844 ⟶ 883:
return 0;
}</langsyntaxhighlight>
Output:
<pre>
Line 876 ⟶ 915:
=={{header|Clojure}}==
 
<syntaxhighlight lang="clojure">
<lang Clojure>
 
(defn iterator [a b]
Line 888 ⟶ 927:
(take 10 ms) ;-> (38 7719 21238 2437 8855 11797 8365 32285 10450 30612)
 
</syntaxhighlight>
</lang>
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang="lisp">(defun make-rng (&key (seed 0) (mode nil))
"returns an RNG according to :seed and :mode keywords
default mode: bsd
Line 904 ⟶ 943:
 
(let ((rng (make-rng :mode 'ms :seed 1)))
(dotimes (x 10) (format t "MS: ~d~%" (funcall rng))))</langsyntaxhighlight>
 
 
Another solution could be:
<langsyntaxhighlight lang="lisp">(defun linear-random (seed &key (times 1) (bounds (expt 2 31)) (multiplier 1103515245) (adder 12345) (divisor 1) (max 2147483647) (min 0))
(loop for candidate = seed then (mod (+ (* multiplier candidate) adder) bounds)
for result = candidate then (floor (/ candidate divisor))
when (and (< result max) (> result min)) collect result into valid-numbers
when (> (length valid-numbers) times) return result))</langsyntaxhighlight>
 
Which defaults to the BSD formula, but can be customized to any formula with keyword arguments, for example:
<langsyntaxhighlight lang="lisp">(format t "Count:~15tBSD:~30tMS:~%~{~{~a~15t~a~30t~a~%~}~}"
(loop for i from 0 upto 5 collect
(list i
(linear-random 0 :times i)
(linear-random 0 :times i :multiplier 214013 :adder 2531011 :max 32767 :divisor (expt 2 16)))))</langsyntaxhighlight>
 
Outputs:
Line 931 ⟶ 970:
 
=={{header|D}}==
<langsyntaxhighlight lang="d">struct LinearCongruentialGenerator {
enum uint RAND_MAX = (1U << 31) - 1;
uint seed = 0;
Line 958 ⟶ 997:
foreach (immutable i; 0 .. 10)
writeln(rnd.randMS);
}</langsyntaxhighlight>
Output:
<pre>12345
Line 985 ⟶ 1,024:
''dc'' has no bitwise operations, so this program uses the modulus operator (<code>2147483648 %</code>) and division (<code>65536 /</code>). Fortunately, ''dc'' numbers cannot overflow to negative, so the modulus calculation involves only non-negative integers.
 
For BSD rand(): <langsyntaxhighlight lang="dc">[*
* lrx -- (random number from 0 to 2147483647)
*
Line 995 ⟶ 1,034:
[* Set seed to 1, then print the first 3 random numbers. *]sz
1 sR
lrx psz lrx psz lrx psz</langsyntaxhighlight>
 
<pre>1103527590
Line 1,001 ⟶ 1,040:
662824084</pre>
 
For Microsoft rand(): <langsyntaxhighlight lang="dc">[*
* lrx -- (random number from 0 to 32767)
*
Line 1,011 ⟶ 1,050:
[* Set seed to 1, then print the first 3 random numbers. *]sz
1 sR
lrx psz lrx psz lrx psz</langsyntaxhighlight>
 
<pre>41
Line 1,020 ⟶ 1,059:
{{libheader| Winapi.Windows}}
{{Trans|C#}}
<syntaxhighlight lang="delphi">
<lang Delphi>
program Linear_congruential_generator;
 
Line 1,093 ⟶ 1,132:
end.
 
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,123 ⟶ 1,162:
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.
<langsyntaxhighlight lang="edsac">
[Linear congruential generators for pseudo-random numbers.
EDSAC program, Initial Orders 2.]
Line 1,256 ⟶ 1,338:
E 15 Z [define entry point]
P F [acc = 0 on entry]
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,285 ⟶ 1,367:
 
=={{header|Elixir}}==
<langsyntaxhighlight lang="elixir">defmodule LCG do
def ms_seed(seed) do
Process.put(:ms_state, seed)
Line 1,319 ⟶ 1,401:
:io.format "~11w~8w~n", [LCG.bsd_rand, LCG.ms_rand]
end)
end)</langsyntaxhighlight>
 
{{out}}
Line 1,352 ⟶ 1,434:
=={{header|Erlang}}==
{{trans|Elixir}}
<langsyntaxhighlight lang="erlang">-module(lcg).
-export([bsd_seed/1, ms_seed/1, bsd_rand/0, ms_rand/0]).
 
Line 1,372 ⟶ 1,454:
ms_seed(0),
io:fwrite("~10s~c~5s~n", ["BSD", 9, "MS"]),
lists:map(fun(_) -> io:fwrite("~10w~c~5w~n", [bsd_rand(),9,ms_rand()]) end, lists:seq(1,10)).</langsyntaxhighlight>
 
{{Out}}
Line 1,389 ⟶ 1,471:
=={{header|ERRE}}==
ERRE doesn't generate the proper output from the BSD constants; it uses double-precision floating point, which is not enough for some of the intermediate products: for exact computation you can use MULPREC program. The BSD series deviates starting with the third value (see sample output below).
<langsyntaxhighlight ERRElang="erre">PROGRAM RNG
 
!$DOUBLE
Line 1,422 ⟶ 1,504:
PRINT(TAB(10);XRND)
END FOR
END PROGRAM</langsyntaxhighlight>
{{out}}
<pre>
Line 1,451 ⟶ 1,533:
=={{header|F_Sharp|F#}}==
 
<langsyntaxhighlight lang="fsharp">module lcg =
let bsd seed =
let state = ref seed
Line 1,463 ⟶ 1,545:
state := (214013 * !state + 2531011) &&& System.Int32.MaxValue
!state / (1<<<16))
</syntaxhighlight>
</lang>
<pre>let rndBSD = lcg.bsd 0;;
let BSD=[for n in [0 .. 9] -> rndBSD()];;
Line 1,478 ⟶ 1,560:
=={{header|Factor}}==
{{works with|Factor|0.98}}
<langsyntaxhighlight lang="factor">USING: fry io kernel lists lists.lazy math prettyprint ;
 
: lcg ( seed a c m quot: ( state -- rand ) -- list )
Line 1,485 ⟶ 1,567:
0 1103515245 12345 2147483648 [ ] lcg ! bsd
0 214013 2531011 2147483648 [ -16 shift ] lcg ! ms
[ 10 swap ltake [ . ] leach nl ] bi@</langsyntaxhighlight>
{{out}}
<pre>
Line 1,512 ⟶ 1,594:
 
=={{header|Forth}}==
<langsyntaxhighlight lang="forth">1 31 lshift 1- constant MAX-RAND-BSD
1 15 lshift 1- constant MAX-RAND-MS
 
Line 1,528 ⟶ 1,610:
;
 
test-random</langsyntaxhighlight>
 
Output:
Line 1,547 ⟶ 1,629:
=={{header|Fortran}}==
{{works with|Fortran|90 and later}}
<langsyntaxhighlight lang="fortran">module lcgs
implicit none
 
Line 1,588 ⟶ 1,670:
write(*, "(2i12)") bsdrand(), msrand()
end do
end program</langsyntaxhighlight>
Output
<pre> BSD MS
Line 1,603 ⟶ 1,685:
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">' version 04-11-2016
' compile with: fbc -s console
 
Line 1,659 ⟶ 1,741:
Print : Print "hit any key to end program"
Sleep
End</langsyntaxhighlight>
{{out}}
<pre>MS generator
Line 1,684 ⟶ 1,766:
794471793
551188310</pre>
 
=={{header|Fōrmulæ}}==
 
{{FormulaeEntry|page=https://formulae.org/?script=examples/Linear_congruential_generator}}
 
'''Solution'''
 
'''Definitions'''
 
[[File:Fōrmulæ - Linear congruential generator 01.png]]
 
[[File:Fōrmulæ - Linear congruential generator 02.png]]
 
'''Test case'''
 
[[File:Fōrmulæ - Linear congruential generator 03.png]]
 
[[File:Fōrmulæ - Linear congruential generator 04.png]]
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 1,720 ⟶ 1,820:
example(0)
example(1)
}</langsyntaxhighlight>
Output:
<pre>
Line 1,741 ⟶ 1,841:
 
=={{header|Haskell}}==
<langsyntaxhighlight lang="haskell">bsd = tail . iterate (\n -> (n * 1103515245 + 12345) `mod` 2^31)
msr = map (`div` 2^16) . tail . iterate (\n -> (214013 * n + 2531011) `mod` 2^31)
 
main = do
print $ take 10 $ bsd 0 -- can take seeds other than 0, of course
print $ take 10 $ msr 0</langsyntaxhighlight>
 
=={{header|Icon}} and {{header|Unicon}}==
The following LCRNG's behave in the same way maintaining the state (seed) from round to round. There is an srand procedure for each lcrng that maintains the seed state and allows the user to assign a new state.
<langsyntaxhighlight Iconlang="icon">link printf
 
procedure main()
Line 1,774 ⟶ 1,874:
procedure rand_MS() #: lcrng
return ishift(srand_MS((214013 * srand_MS() + 2531011) % 2147483648),-16)
end</langsyntaxhighlight>
 
{{libheader|Icon Programming Library}}
Line 1,781 ⟶ 1,881:
=={{header|J}}==
'''Solution:'''
<langsyntaxhighlight lang="j">lcg=: adverb define
0 m lcg y NB. default seed of 0
:
Line 1,789 ⟶ 1,889:
 
rand_bsd=: (1103515245 12345 , <.2^31) lcg
rand_ms=: (2^16) <.@:%~ (214013 2531011 , <.2^31) lcg</langsyntaxhighlight>
'''Example Use:'''
<langsyntaxhighlight lang="j"> rand_bsd 10
12345 1406932606 654583775 1449466924 229283573 1109335178 1051550459 1293799192 794471793 551188310
654583775 rand_bsd 4
Line 1,798 ⟶ 1,898:
38 7719 21238 2437 8855 11797 8365 32285 10450 30612
1 rand_ms 5 NB. seed of 1
41 18467 6334 26500 19169</langsyntaxhighlight>
 
=={{header|Java}}==
{{works with|Java|8}}
<langsyntaxhighlight lang="java">import java.util.stream.IntStream;
import static java.util.stream.IntStream.iterate;
 
Line 1,824 ⟶ 1,924:
.map(i -> i >> 16);
}
}</langsyntaxhighlight>
 
<pre>BSD:
Line 1,851 ⟶ 1,951:
 
=={{header|jq}}==
The Go implementation of jq (gojq) supports unlimited-precision integer arithmetic and therefore linear congruential generators (LCGs) can be trivially written for gojq.
Currently, jq arithmetic is based on IEEE 754 64-bit numbers. As a result, it is trivial to implement the Microsoft linear congruential generator (LCG), but the BSD generator requires some kind of "big integer" support. In this section, therefore, we first present functions to support the Microsoft LCG, and then present functions to support the LCG on the assumption that a suitable jq "BigInt" library is available.
 
The C implementation of jq, however, currently uses IEEE 754 64-bit numbers for arithmetic, so a BSD generator for the C implementation of jq would require some kind of "big integer" support.
 
In this entry, therefore, we first present functions for the Microsoft LCG that can be used with jq or gojq, and then present functions to support the BSD generator on the assumption that a suitable "BigInt" library is available.
====Microsoft LCG====
<langsyntaxhighlight lang="jq"># 15-bit integers generated using the same formula as rand()
# from the Microsoft C Runtime.
# Input: [ count, state, rand ]
Line 1,866 ⟶ 1,970:
| next_rand_Microsoft # the seed is not so random
| recurse(if .[0] < n then next_rand_Microsoft else empty end)
| .[2];</langsyntaxhighlight>
'''Example''':
rand_Microsoft(1;5)
{{out}}
<langsyntaxhighlight lang="sh">41
18467
6334
26500
19169</langsyntaxhighlight>
====BSD LCG====
The following code has been tested with the "BigInt" library at [https://gist.github.com/pkoppstein/d06a123f30c033195841].
<langsyntaxhighlight lang="jq"># BSD rand()
# Input: [count, previous]
def next_rand_berkeley:
Line 1,890 ⟶ 1,994:
| next_rand_berkeley # skip the seed itself
| recurse(if .[0] < n then next_rand_berkeley else empty end)
| .[1];</langsyntaxhighlight>
'''Example''':
rand_berkeley(1;5)
{{out}}
<langsyntaxhighlight lang="sh">1103527590
377401575
662824084
1147902781
2035015474</langsyntaxhighlight>
 
=={{header|Julia}}==
<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.
<langsyntaxhighlight lang="julia">using Printf
 
function getlgc(r::Integer, a::Integer, c::Integer, m::Integer, sh::Integer)
Line 1,925 ⟶ 2,029:
for _ in 1:nrep
@printf("%14d\n", msrand())
end</langsyntaxhighlight>
 
{{out}}
Line 1,953 ⟶ 2,057:
 
=={{header|K}}==
<langsyntaxhighlight Klang="k"> bsd:{1_ y{((1103515245*x)+12345)!(_2^31)}\x}
ms:{1_(y{_(((214013*x)+2531011)!(_2^31))}\x)%(_2^16)}
 
Line 1,959 ⟶ 2,063:
12345 1406932606 654583775 1449466924 229283573 1109335178 1051550459 1293799192 794471793 551188310
ms[0;10]
38 7719 21238 2437 8855 11797 8365 32285 10450 30612</langsyntaxhighlight>
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.1.3
 
class Lcg(val a: Long, val c: Long, val m: Long, val d: Long, val s: Long) {
Line 1,980 ⟶ 2,084:
val msc = Lcg(214013, 2531011, 1 shl 31, 1 shl 16, 0)
for (i in 1..10) println("${msc.nextInt()}")
}</langsyntaxhighlight>
 
{{out}}
Line 2,010 ⟶ 2,114:
 
=={{header|Liberty BASIC}}==
<syntaxhighlight lang="lb">
<lang lb>
'by default these are 0
global BSDState
Line 2,034 ⟶ 2,138:
randMS = int(MSState / 2 ^ 16)
end function
</syntaxhighlight>
</lang>
 
=={{header|Logo}}==
Line 2,040 ⟶ 2,144:
Note that, perhaps ironically, [[UCB Logo]], as of version 6.0, doesn't generate the proper output from the BSD constants; it uses double-precision floating point, which is not enough for some of the intermediate products. In UCBLogo, the BSD series deviates starting with the third value (see sample output below).
 
<langsyntaxhighlight Logolang="logo">; Configuration parameters for Microsoft and BSD implementations
make "LCG_MS [214013 2531011 65536 2147483648]
make "LCG_BSD [1103515245 12345 1 2147483648]
Line 2,069 ⟶ 2,173:
print []
]
bye</langsyntaxhighlight>
 
Output:<pre>12345
Line 2,110 ⟶ 2,214:
This requires Lua 5.3 or later because previous versions didn't have support for large integers or integral arithmetic operations.
 
<langsyntaxhighlight lang="lua">local RNG = {
new = function(class, a, c, m, rand)
local self = setmetatable({}, class)
Line 2,136 ⟶ 2,240:
print(("\t%10d"):format(ms.rnd()))
end
</syntaxhighlight>
</lang>
 
{{Out}}
Line 2,163 ⟶ 2,267:
</pre>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">BSDrand[x_] := Mod[x*1103515245 + 12345, 2147483648]
NestList[BSDrand, 0, 10]
-> {0, 12345, 1406932606, 654583775, 1449466924, 229283573, 1109335178, 1051550459, 1293799192, 794471793, 551188310}
Line 2,170 ⟶ 2,274:
MSrand[x_] := Mod[x*214013 + 2531011, 2147483648]
BitShiftRight[ NestList[MSrand, 0, 10], 16]
-> {0, 38, 7719, 21238, 2437, 8855, 11797, 8365, 32285, 10450, 30612}</langsyntaxhighlight>
 
=={{header|Maxima}}==
<langsyntaxhighlight lang="maxima">seed: 0$
ms_rand() := quotient(seed: mod(214013 * seed + 2531011, 2147483648), 65536)$
makelist(ms_rand(), 20); /* see http://oeis.org/A096558 */
Line 2,186 ⟶ 2,290:
[12345, 1406932606, 654583775, 1449466924, 229283573, 1109335178, 1051550459,
1293799192, 794471793, 551188310, 803550167, 1772930244, 370913197, 639546082, 1381971571,
1695770928, 2121308585, 1719212846, 996984527, 1157490780]</langsyntaxhighlight>
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">proc bsdRand(seed: int): iterator: int =
var state = seed
result = iterator: int =
Line 2,220 ⟶ 2,324:
inc count
if count == 10:
break</langsyntaxhighlight>
 
{{out}}
Line 2,246 ⟶ 2,350:
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 2,251 ⟶ 2,383:
Function genLCG returns a block object that, when performed, will return the next random number from the LCG.
 
<langsyntaxhighlight Oforthlang="oforth">: genLCG(a, c, m, seed)
| ch |
Channel newSize(1) dup send(seed) drop ->ch
#[ ch receive a * c + m mod dup ch send drop ] ;</langsyntaxhighlight>
 
{{out}}
Line 2,285 ⟶ 2,417:
=={{header|PARI/GP}}==
Note that up to PARI/GP version 2.4.0, <code>random()</code> used a linear congruential generator.
<langsyntaxhighlight lang="parigp">BSDseed=Mod(1,1<<31);
MSFTseed=Mod(1,1<<31);
BSD()=BSDseed=1103515245*BSDseed+12345;lift(BSDseed);
MSFT()=MSFTseed=214013*MSFTseed+2531011;lift(MSFTseed)%(1<<31);</langsyntaxhighlight>
 
=={{header|Pascal}}==
<langsyntaxhighlight lang="pascal">Program LinearCongruentialGenerator(output);
{$mode iso}
var
Line 2,325 ⟶ 2,457:
writeln(bsdrand:12, msrand:12);
end.
</syntaxhighlight>
</lang>
Output:
<pre> BSD MS
Line 2,340 ⟶ 2,472:
 
=={{header|Perl}}==
Creates a magic scalar whose value is next in the LCG sequence when read.<langsyntaxhighlight lang="perl">use strict;
package LCG;
 
Line 2,379 ⟶ 2,511:
 
print "\nMS:\n";
print "$rand\n" for 1 .. 10;</langsyntaxhighlight>output<syntaxhighlight lang="text">BSD:
12345
1406932606
Line 2,401 ⟶ 2,533:
32285
10450
30612</langsyntaxhighlight>
 
=={{header|Phix}}==
{{libheader|Phix/mpfr}}
As per the comments, I had to resort to gmp to get BSDrnd() to work on 32-bit.
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang Phix>atom seed
<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>
include builtins/mpfr.e
<span style="color: #008080;">include</span> <span style="color: #000000;">builtins</span><span style="color: #0000FF;">/</span><span style="color: #004080;">mpfr</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span>
function BSDrnd()
-- oh dear, native only works on 64-bit,
<span style="color: #008080;">function</span> <span style="color: #000000;">BSDrnd</span><span style="color: #0000FF;">()</span>
-- as per ERRE and UCBLogo above on 32-bit...
<span style="color: #000080;font-style:italic;">-- oh dear, native only works on 64-bit,
-- seed = remainder(1103515245 * seed + 12345, #8000_0000)
-- so,as resortper toERRE gmp,and withUCBLogo theabove addedon twist than both32-bit...
-- seed = -- remainder(1103515245 and* #8000_0000seed are+ greater12345, than 1GB and#8000_0000)
-- thereforeso, aresort smidgeto toogmp, bigwith &the needadded sometwist extrathan help...both
-- 1103515245 and #8000_0000 are greater than 1GB and
mpz z = mpz_init(seed),
-- therefore a smidge too big & need some extra help...</span>
h8 = mpz_init("2147483648") -- (ie #8000_0000)
<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>
mpz_mul_si(z,z,5)
<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>
mpz_mul_si(z,z,1103515245/5) -- (do in two <1GB factors)
<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>
mpz_add_si(z,z,12345)
<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>
mpz_fdiv_r(z,z,h8)
<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>
seed = mpz_get_atom(z)
<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>
return seed
<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>
end function
<span style="color: #008080;">return</span> <span style="color: #000000;">seed</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
function MSrnd()
seed = and_bits(seed*214013+2531011,#7FFFFFFF)
<span style="color: #008080;">function</span> <span style="color: #000000;">MSrnd</span><span style="color: #0000FF;">()</span>
return floor(seed/power(2,16))
<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>
end function
<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>
seed = 0
?"BSDrnd"
<span style="color: #000000;">seed</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
for i=1 to 10 do printf(1,"%d\n",BSDrnd()) end for
<span style="color: #0000FF;">?</span><span style="color: #008000;">"BSDrnd"</span>
seed = 0
<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>
?"MSrnd"
<span style="color: #000000;">seed</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
for i=1 to 10 do printf(1,"%d\n",MSrnd()) end for</lang>
<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,466 ⟶ 2,601:
=={{header|PHP}}==
{{works with|PHP|5.3+}}
<langsyntaxhighlight lang="php"><?php
function bsd_rand($seed) {
return function() use (&$seed) {
Line 2,490 ⟶ 2,625:
echo $lcg(), " ";
echo "\n";
?></langsyntaxhighlight>
 
=={{header|Picat}}==
===Methods as hard coded predicates===
<syntaxhighlight lang="picat">go =>
 
% BSD
println(bsd=[bsd() : _ in 1..10]),
bsd_seed(1),
println(bsd2=[bsd() : _ in 1..10]),
 
% MS
println(ms=[ms() : _ in 1..10]),
ms_seed(1),
println(ms2=[ms() : _ in 1..10]),
 
nl.
 
% BSD
bsd_seed(Seed) =>
get_global_map().put(bsd_state, Seed).
bsd = Rand =>
M = get_global_map(),
Seed = cond(M.has_key(bsd_state), M.get(bsd_state),0),
Rand = (1103515245*Seed + 12345) mod 2**31,
M.put(bsd_state,Rand).
% Microsoft
ms_seed(Seed) =>
get_global_map().put(ms_state, Seed).
ms = Rand div 2**16 =>
M = get_global_map(),
Seed = cond(M.has_key(ms_state),M.get(ms_state),0),
Rand = ((214013*Seed + 2531011) mod 2**31),
M.put(ms_state,Rand).</syntaxhighlight>
 
{{out}}
<pre>bsd = [12345,1406932606,654583775,1449466924,229283573,1109335178,1051550459,1293799192,794471793,551188310]
bsd2 = [1103527590,377401575,662824084,1147902781,2035015474,368800899,1508029952,486256185,1062517886,267834847]
ms = [38,7719,21238,2437,8855,11797,8365,32285,10450,30612]
ms2 = [41,18467,6334,26500,19169,15724,11478,29358,26962,24464]</pre>
 
===Generalized version===
Using a global global map for setting/setting seeds etc.
<syntaxhighlight lang="picat">go2 =>
 
% BSD
lcg_init(bsd,1103515245,12345,2**31,1),
println([lcg(bsd) : _ in 1..10]),
 
lcg_init(bsd,1,1103515245,12345,2**31,1),
println([lcg(bsd) : _ in 1..10]),
 
% MS
lcg_init(ms,214013,2531011,2**31,2**16),
println([lcg(ms) : _ in 1..10]),
 
lcg_init(ms,1,214013,2531011,2**31,2**16),
println([lcg(ms) : _ in 1..10]),
 
% unknown (-> error)
println([lcg(unknown) : _ in 1..10]),
 
nl.
 
% default seed is 0
lcg_init(Type,Multiplier,Adder,Mod,OutputDivisor) =>
lcg_init(Type,0,Multiplier,Adder,Mod,OutputDivisor).
 
lcg_init(Type,Seed,Multiplier,Adder,Mod,OutputDivisor) =>
get_global_map().put(Type,
new_map([seed=Seed,multiplier=Multiplier,adder=Adder,mod=Mod,outputDivisor=OutputDivisor])).
 
lcg(Type) = Rand div M.get(outputDivisor) =>
if not get_global_map().has_key(Type) then
throw $lcg(Type,unknown_LCG_type)
end,
M = get_global_map().get(Type),
Rand = ((M.get(multiplier)*M.get(seed) + M.get(adder)) mod M.get(mod)),
M.put(seed,Rand),
get_global_map().put(Type,M).</syntaxhighlight>
 
{{out}}
<pre>[12345,1406932606,654583775,1449466924,229283573,1109335178,1051550459,1293799192,794471793,551188310]
[1103527590,377401575,662824084,1147902781,2035015474,368800899,1508029952,486256185,1062517886,267834847]
[38,7719,21238,2437,8855,11797,8365,32285,10450,30612]
[41,18467,6334,26500,19169,15724,11478,29358,26962,24464]
*** lcg(unknown,unknown_LCG_type)</pre>
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(zero *BsdSeed *MsSeed)
 
(de bsdRand ()
Line 2,502 ⟶ 2,724:
(>> 16
(setq *MsSeed
(& (+ 2531011 (* 214013 *MsSeed)) `(dec (** 2 31))) ) ) )</langsyntaxhighlight>
Output:
<pre>: (do 7 (printsp (bsdRand)))
Line 2,511 ⟶ 2,733:
 
=={{header|PL/I}}==
<syntaxhighlight lang="text">
(nofixedoverflow, nosize):
LCG: procedure options (main);
Line 2,540 ⟶ 2,762:
 
end LCG;
</syntaxhighlight>
</lang>
OUTPUT:
<pre>
Line 2,567 ⟶ 2,789:
 
=={{header|PowerShell}}==
<langsyntaxhighlight lang="powershell">
Function msstate{
Param($current_seed)
Line 2,592 ⟶ 2,814:
$seed = randBSD($seed)
Write-Host $seed}
</syntaxhighlight>
</lang>
 
{{Out}}
Line 2,611 ⟶ 2,833:
 
=={{header|PureBasic}}==
<langsyntaxhighlight lang="purebasic">Procedure ms_LCG(seed.q = -1)
Static state.q
If seed >= 0
Line 2,647 ⟶ 2,869:
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
CloseConsole()
EndIf</langsyntaxhighlight>
Sample output:
<pre>BSD (seed = 1)
Line 2,664 ⟶ 2,886:
 
=={{header|Python}}==
<langsyntaxhighlight lang="python">def bsd_rand(seed):
def rand():
rand.seed = (1103515245*rand.seed + 12345) & 0x7fffffff
Line 2,676 ⟶ 2,898:
return rand.seed >> 16
rand.seed = seed
return rand</langsyntaxhighlight>
{{works with|Python|3.x}}
<langsyntaxhighlight lang="python">def bsd_rand(seed):
def rand():
nonlocal seed
Line 2,690 ⟶ 2,912:
seed = (214013*seed + 2531011) & 0x7fffffff
return seed >> 16
return rand</langsyntaxhighlight>
 
=={{header|Quackery}}==
 
<syntaxhighlight lang="quackery"> [ number$
10 over size -
space swap of
swap join echo$ ] is echonum ( n --> )
 
[ stack 0 ] is BSD-seed ( --> n )
 
[ BSD-seed take
1103515245 *
12345 +
hex 7FFFFFFF &
dup BSD-seed put ] is BSD-rand ( --> n )
 
[ stack 0 ] is MCR-seed ( --> n )
 
[ MCR-seed take
214013 *
2531011 +
hex 7FFFFFFF &
dup MCR-seed put
16 >> ] is MCR-rand ( --> n )
 
say " BSD-rand MCR-rand" cr
10 times
[ BSD-rand echonum
MCR-rand echonum cr ]</syntaxhighlight>
 
{{out}}
 
<pre> BSD-rand MCR-rand
12345 38
1406932606 7719
654583775 21238
1449466924 2437
229283573 8855
1109335178 11797
1051550459 8365
1293799192 32285
794471793 10450
551188310 30612
</pre>
 
=={{header|R}}==
<langsyntaxhighlight lang="r">library(gmp) # for big integers
 
rand_BSD <- function(n = 1) {
Line 2,706 ⟶ 2,972:
i <- i + 1
}
as.integer(x)
x
}
 
seed <- 0
rand_BSD(10)
## [1] 12345 1406932606 654583775 1449466924 229283573 1109335178
## Big Integer ('bigz') object of length 10:
## [7] 1051550459 1293799192 794471793 551188310
## [1] 12345 1406932606 654583775 1449466924 229283573 1109335178
## [7] 1051550459 1293799192 794471793 551188310
 
rand_MS <- function(n = 1) {
Line 2,726 ⟶ 2,991:
i <- i + 1
}
as.bigzinteger(x / 2^16)
}
 
seed <- 0
rand_MS(10)
## [1] 38 7719 21238 2437 8855 11797 8365 32285 10450 30612</syntaxhighlight>
## Big Integer ('bigz') object of length 10:
## [1] 38 7719 21238 2437 8855 11797 8365 32285 10450 30612</lang>
 
=={{header|Racket}}==
Line 2,738 ⟶ 3,002:
The following solution uses generators and transcribes the mathematical formulas above directly. It does not attempt to be efficient.
 
<langsyntaxhighlight lang="racket">
#lang racket
(require racket/generator)
Line 2,759 ⟶ 3,023:
(define bsd-rand (rand bsd-update identity))
(define ms-rand (rand ms-update (λ (x) (quotient x (expt 2 16)))))
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
Line 2,766 ⟶ 3,030:
We'll define subroutines implementing the LCG algorithm for each version. We'll make them return a lazy list.
 
<syntaxhighlight lang="raku" perl6line>constant modulus = 2**31;
sub bsd {
$^seed, ( 1103515245 * * + 12345 ) % modulus ... *
Line 2,780 ⟶ 3,044:
say "\nMS LCG first 10 values (first one is the seed):";
.say for ms(0)[^10];</langsyntaxhighlight>
 
<pre>BSD LCG first 10 values (first one is the seed):
Line 2,807 ⟶ 3,071:
 
=={{header|REXX}}==
<langsyntaxhighlight 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 */
numeric digits 20 /*use enough dec. digs for the multiply*/
Line 2,828 ⟶ 3,092:
" rand" right(ms % two@@16, 6)
end /*j*/
end /*seed*/ /*stick a fork in it, we're all done. */</langsyntaxhighlight>
{{out|output|text= &nbsp; &nbsp; (shown at five-sixth size.) }}
<pre style="font-size:84%">
Line 2,873 ⟶ 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,878 ⟶ 3,164:
You can create multiple instances of LCG::Berkeley or LCG::Microsoft. Each instance privately keeps the original seed in @seed, and the current state in @r. Each class resembles the core Random class, but with fewer features. The .new method takes a seed. The #rand method returns the next random number. The #seed method returns the original seed.
 
<langsyntaxhighlight lang="ruby">module LCG
module Common
# The original seed of this generator.
Line 2,907 ⟶ 3,193:
end
end
end</langsyntaxhighlight>
 
The next example sets the seed to 1, and prints the first 5 random numbers.
 
<langsyntaxhighlight lang="ruby">lcg = LCG::Berkeley.new(1)
p (1..5).map {lcg.rand}
# prints [1103527590, 377401575, 662824084, 1147902781, 2035015474]
Line 2,917 ⟶ 3,203:
lcg = LCG::Microsoft.new(1)
p (1..5).map {lcg.rand}
# prints [41, 18467, 6334, 26500, 19169]</langsyntaxhighlight>
 
=={{header|Run BASIC}}==
<langsyntaxhighlight lang="runbasic">global bsd
global ms
print "Num ___Bsd___";chr$(9);"__Ms_"
Line 2,935 ⟶ 3,221:
ms = (214013 * ms + 2531011) mod (2 ^ 31)
msRnd = int(ms / 2 ^ 16)
end function</langsyntaxhighlight>
<pre>
Num ___Bsd___ __Ms_
Line 2,950 ⟶ 3,236:
 
=={{header|Rust}}==
<langsyntaxhighlight lang="rust">extern crate rand;
 
pub use rand::{Rng, SeedableRng};
Line 3,020 ⟶ 3,306:
println!("{}", ms.gen::<bool>());
println!("{}", ms.gen_ascii_chars().take(15).collect::<String>());
}</langsyntaxhighlight>
 
=={{header|Scala}}==
<langsyntaxhighlight lang="scala">object LinearCongruentialGenerator {
def bsdRandom(rseed:Int):Iterator[Int]=new Iterator[Int]{
var seed=rseed
Line 3,047 ⟶ 3,333:
println("MS : "+ toString( msRandom(1)))
}
}</langsyntaxhighlight>
{{out}}
<pre>-- seed 0 --
Line 3,066 ⟶ 3,352:
 
=={{header|Scheme}}==
For R7RS Scheme.
<lang scheme>(define ((bsd-rand seed)) (set! seed (remainder (+ (* 1103515245 seed) 12345) 2147483648)) seed)
<syntaxhighlight lang="scheme">(import (scheme base)
(scheme write))
 
(define ((bsd-rand state))
(define ((msvcrt-rand seed)) (set! seed (remainder (+ (* 214013 seed) 2531011) 2147483648)) (quotient seed 65536))
(set! state (remainder (+ (* 1103515245 state) 12345) 2147483648))
state)
 
(define ((msvcrt-rand state))
(set! state (remainder (+ (* 214013 state) 2531011) 2147483648))
(quotient state 65536))
 
; auxiliary function to get a list of 'n random numbers from generator 'r
(define (rand-list r n) = (if (zero? n) '() (cons (r) (rand-list r (- n 1)))))
(if (zero? n) '() (cons (r) (rand-list r (- n 1)))))
 
(display (rand-list (bsd-rand 0) 10))
; (12345 1406932606 654583775 1449466924 229283573 1109335178 1051550459 1293799192 794471793 551188310)
 
(newline)
(rand-list (msvcrt-rand 0) 10)
 
; (38 7719 21238 2437 8855 11797 8365 32285 10450 30612)</lang>
(display (rand-list (msvcrt-rand 0) 10))
; (38 7719 21238 2437 8855 11797 8365 32285 10450 30612)</syntaxhighlight>
 
=={{header|Seed7}}==
Line 3,087 ⟶ 3,384:
[http://seed7.sourceforge.net/libraries/array.htm#rand%28in_arrayType%29 rand(arr)]. This function selects a random element from an array.
 
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
include "bigint.s7i";
 
Line 3,117 ⟶ 3,414:
writeln(bsdRand lpad 12 <& msRand lpad 12);
end for;
end func;</langsyntaxhighlight>
 
Output:
Line 3,137 ⟶ 3,434:
Uses the Random library provided by SequenceL to create new Random Number Generators
 
<syntaxhighlight lang="sequencel">
<lang sequenceL>
import <Utilities/Random.sl>;
 
Line 3,164 ⟶ 3,461:
(Value : newSeed / 65536,
Generator : (Seed : newSeed, RandomMin : RG.RandomMin, RandomMax : RG.RandomMax, NextFunction : RG.NextFunction));
</syntaxhighlight>
</lang>
Output
<pre>
Line 3,173 ⟶ 3,470:
=={{header|Sidef}}==
{{trans|Ruby}}
<langsyntaxhighlight lang="ruby">module LCG {
 
# Creates a linear congruential generator and remembers the initial seed.
Line 3,202 ⟶ 3,499:
 
var lcg2 = LCG::Microsoft(1)
say 5.of { lcg2.rand }</langsyntaxhighlight>
{{out}}
<pre>
Line 3,210 ⟶ 3,507:
 
=={{header|Sparkling}}==
<langsyntaxhighlight lang="sparkling">var states = {
"BSD": 0,
"MS": 0
Line 3,229 ⟶ 3,526:
function Microsoft_rand() {
return (states.MS = (214013 * states.MS + 2531011) % (1 << 31)) % (1 << 15);
}</langsyntaxhighlight>
 
Output seen after seeding both generators with 0:
 
<langsyntaxhighlight lang="sparkling">spn:8> Microsoft_seed(0);
spn:9> Microsoft_rand()
= 7875
Line 3,254 ⟶ 3,551:
= 1449466924
spn:19> BSD_rand()
= 229283573</langsyntaxhighlight>
 
=={{header|Standard ML}}==
<syntaxhighlight lang="sml">local
open Word32
in
fun bsdLcg (seed : int) : int =
toInt (andb (0w1103515245 * fromInt seed + 0w12345, 0wx7fffffff))
fun mscLcg (seed : word) : int * word =
let
val state = andb (0w214013 * seed + 0w2531011, 0wx7fffffff)
in
(toInt (>> (state, 0w16)), state)
end
end</syntaxhighlight>
;Test code<nowiki>:</nowiki>
<syntaxhighlight lang="sml">fun test1 rand =
(print (" " ^ Int.toString rand); rand)
 
fun test2 (rand, state) =
(print (" " ^ Int.toString rand); state)
 
fun doTimes (_, 0, state) = ()
| doTimes (f, n, state) = doTimes (f, n - 1, f state)
 
val () = print "BSD:\n"
val () = doTimes (test1 o bsdLcg, 7, 0)
val () = print "\nMSC:\n"
val () = doTimes (test2 o mscLcg, 7, 0w0)
val () = print "\n"</syntaxhighlight>
{{out}}
<pre>BSD:
12345 1406932606 654583775 1449466924 229283573 1109335178 1051550459
MSC:
38 7719 21238 2437 8855 11797 8365</pre>
 
=={{header|Stata}}==
 
<langsyntaxhighlight lang="stata">mata
function rand_bsd(u) {
m = 65536
Line 3,282 ⟶ 3,613:
 
rand_seq(&rand_bsd(),1,10)
rand_seq(&rand_ms(),0,10)</langsyntaxhighlight>
 
'''Output''': compare with OEIS '''[http://oeis.org/A096553 A096553]''' and '''[http://oeis.org/A096558 A096558]'''.
Line 3,317 ⟶ 3,648:
=={{header|Swift}}==
 
<langsyntaxhighlight Swiftlang="swift">import Cocoa
 
class LinearCongruntialGenerator {
Line 3,363 ⟶ 3,694:
{
print(BSDLinearCongruntialGenerator.random())
}</langsyntaxhighlight>
{{out}}<pre>Microsft Rand:
38
Line 3,390 ⟶ 3,721:
=={{header|Tcl}}==
Using an object-oriented solution, inspired by (but not a translation of) the [[#Ruby|Ruby]] solution above.
<langsyntaxhighlight lang="tcl">package require Tcl 8.6
 
# General form of a linear-congruential RNG
Line 3,419 ⟶ 3,750:
next $initialSeed 214013 2531011 [expr {2**31}] [expr {2**16}]
}
}</langsyntaxhighlight>
Demo code:
<langsyntaxhighlight lang="tcl">proc sample rng {foreach - {1 2 3 4 5} {lappend r [$rng rand]}; join $r ", "}
puts BSD:\t\[[sample [BSDRNG new 1]]\]
puts MS:\t\[[sample [MSRNG new 1]]\]</langsyntaxhighlight>
Output:
<pre>
Line 3,432 ⟶ 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,466 ⟶ 3,797:
m = Pop() % (2 ^ 31) ' Now we got a number less than 2^31
Push m / (2 ^ 16) ' So we can complete the operation
Return</langsyntaxhighlight>
{{out}}
<pre>BSD
Line 3,497 ⟶ 3,828:
=={{header|UNIX Shell}}==
 
<langsyntaxhighlight lang="bash">#! /bin/bash
 
function BSD() {
Line 3,521 ⟶ 3,852:
 
output BSD
output MS</langsyntaxhighlight>
 
{{out}}
Line 3,552 ⟶ 3,883:
 
=={{header|VBA}}==
<langsyntaxhighlight lang="vb">Public stateBSD As Variant
Public stateMS As Variant
Private Function bsd() As Long
Line 3,577 ⟶ 3,908:
Debug.Print Format(bsd, "@@@@@@@@@@"), Format(ms, "@@@@@")
Next i
End Sub</langsyntaxhighlight>{{out}}
<pre> BSD MS
12345 38
Line 3,595 ⟶ 3,926:
{{libheader|Wren-fmt}}
Some of the intermediate calculations here require integers >= 2^53 so we need to use BigInt.
<langsyntaxhighlight ecmascriptlang="wren">import "./big" for BigInt
import "./fmt" for Fmt
 
// basic linear congruential generator
Line 3,624 ⟶ 3,955:
 
example.call(0)
example.call(1)</langsyntaxhighlight>
 
{{out}}
Line 3,650 ⟶ 3,981:
 
First example using integer instructions.
<langsyntaxhighlight lang="asm">;x86-64 assembly code for Microsoft Windows
;Tested in windows 7 Enterprise Service Pack 1 64 bit
;With the AMD FX(tm)-6300 processor
Line 3,837 ⟶ 4,168:
 
mov rcx,1
call exit</langsyntaxhighlight>
 
Second example using AVX instructions.
{{incorrect|X86 Assembly|It will not produce output identical to that of the Microsoft rand() function.}}
<langsyntaxhighlight lang="asm">;x86-64 assembly code for Microsoft Windows
;Tested in windows 7 Enterprise Service Pack 1 64 bit
;With the AMD FX(tm)-6300 processor
Line 4,084 ⟶ 4,415:
 
mov rcx,1
call exit</langsyntaxhighlight>
 
{{out|Sample}}
Line 4,146 ⟶ 4,477:
[[File:LCG2XPL0.gif|right]]
 
<langsyntaxhighlight XPL0lang="xpl0">include c:\cxpl\codes;
int R;
 
Line 4,174 ⟶ 4,505:
N:= ChIn(1); \wait for keystoke
SetVid(3); \restore normal text mode
]</langsyntaxhighlight>
 
=={{header|zkl}}==
<langsyntaxhighlight lang="zkl">var [private] seed = 0;
fcn srand(s){ seed = s }
 
Line 4,190 ⟶ 4,521:
const A=214013, C=2531011, TWO16=(1).shiftLeft(16);
fcn rand{ (seed = (seed * A + C) % TWO31) / TWO16 }
#endif</langsyntaxhighlight>
<langsyntaxhighlight lang="zkl">srand(0);
println(rand(),",",rand(),",",rand());</langsyntaxhighlight>
{{out}}
<pre>
1,969

edits