Linear congruential generator: Difference between revisions
Added Easylang
(Added Easylang) |
|||
(10 intermediate revisions by 8 users not shown) | |||
Line 39:
=={{header|11l}}==
<
seed = 0
Int a, c, m
Line 61:
print(‘MS RAND:’)
L 5
print(ms_rnd() >> 16)</
{{out}}
Line 81:
=={{header|360 Assembly}}==
<
LINCONG CSECT
USING LINCONG,R12
Line 118:
XDEC DS CL12
YREGS
END LINCONG</
{{out}}
<pre>
Line 137:
We first specify a generic package LCG:
<
type Base_Type is mod <>;
Multiplyer, Adder: Base_Type;
Line 147:
-- changes the state and outputs the result
end LCG;</
Then we provide a generic implementation:
<
State: Base_Type := Base_Type'First;
Line 166:
end Random;
end LCG;</
Next, we define the MS- and BSD-instantiations of the generic package:
<
procedure Run_LCGs is
Line 189:
Ada.Text_IO.Put_Line(M31'Image(MS_Rand.Random));
end loop;
end Run_LCGs;</
Finally, we run the program, which generates the following output (note that the first ten lines are from the BSD generator, the next ten from the MS generator):
Line 215:
=={{header|ALGOL 68}}==
<
BEGIN
COMMENT
Line 295:
srand (0)
END
</syntaxhighlight>
{{out}}
<pre>
Line 322:
=={{header|AutoHotkey}}==
<
Loop, 10
BSD .= "`t" (a := BSD(a)) "`n"
Line 337:
Seed := Mod(214013 * Seed + 2531011, 2147483648)
return, [Seed, Seed // 65536]
}</
'''Output:'''
<pre>BSD:
Line 363:
30612</pre>
=={{header|Batch File}}==
<syntaxhighlight lang="dos">@echo off & setlocal enabledelayedexpansion
echo BSD Rand
Line 388 ⟶ 387:
set p2= %2
echo %p1:~-2% %p2:~-10%
goto:eof</syntaxhighlight>
'''Output:'''
<pre>
Line 419 ⟶ 416:
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<
PRINT "MS generator:"
dummy% = FNrandMS(0)
Line 452 ⟶ 449:
DEF FNmuladd(A%,B%,C%) : PRIVATE M% : LOCAL P% : IF M% = 0 DIM P% 8
IF P% THEN [OPT 0 : .M% mul ebx : add eax,ecx : btr eax,31 : ret :]
= USR M%</
'''Output:'''
<pre>
Line 486 ⟶ 483:
As with dc, bc has no bitwise operators.
<
define rand() {
Line 504 ⟶ 501:
randseed = 1
rand(); rand(); rand(); print "\n"</
=={{header|Befunge}}==
This required a bit of trickery to handle signed overflow and negative division in a portable way. It still won't work on all implementations, though. In particular Javascript-based interpreters can't handle the BSD formula because of the way Javascript numbers lose their least significant digits when they become too large.
<
v $$_^#!\-1:\%***:*::*882 ++*"yf"3***+***+*<
>025*>\:488**:*/:0\`6"~7"+:*+01-2/-*+."O?+"55v
@ $$_^#!\-1:\%***:*::*882 ++***" ''4C"*+2**,+<</
{{out}}
Line 539 ⟶ 536:
=={{header|Bracmat}}==
<
& 2^-16:?rshift
& (randBSD=mod$(!seed*1103515245+12345.!RANDMAX):?seed)
Line 554 ⟶ 551:
& 0:?i
& whl'(1+!i:~>10:?i&out$!randMS)
)</
Output:
Line 583 ⟶ 580:
=={{header|C}}==
In a pretended lib style, this code produces a rand() function depends on compiler macro: <code>gcc -DMS_RAND</code> uses MS style, otherwise it's BSD rand by default.
<
/* always assuming int is at least 32 bits */
Line 623 ⟶ 620:
return 0;
}</
=={{header|C sharp|C#}}==
{{works with|C sharp|C#|6+}}
<!-- By Martin Freedman, 17/01/2018 -->
<
using System.Collections.Generic;
using System.Linq;
Line 663 ⟶ 660:
}
}
}</
Produces:
<pre>BSD next 10 Random
Line 689 ⟶ 686:
</pre>
From a Free Cell Deal solution
<syntaxhighlight lang="csharp">
using System;
using System.Collections.Generic;
Line 757 ⟶ 754:
}
}
</syntaxhighlight>
Output:
<pre>Microsoft
Line 785 ⟶ 782:
=={{header|C++}}==
<
//--------------------------------------------------------------------------------------------------
Line 835 ⟶ 832:
return 0;
}
//--------------------------------------------------------------------------------------------------</
Output:
<pre>
Line 867 ⟶ 864:
; C++11
{{works with|C++11}}
<
#include <random>
Line 886 ⟶ 883:
return 0;
}</
Output:
<pre>
Line 918 ⟶ 915:
=={{header|Clojure}}==
<syntaxhighlight lang="clojure">
(defn iterator [a b]
Line 930 ⟶ 927:
(take 10 ms) ;-> (38 7719 21238 2437 8855 11797 8365 32285 10450 30612)
</syntaxhighlight>
=={{header|Common Lisp}}==
<
"returns an RNG according to :seed and :mode keywords
default mode: bsd
Line 946 ⟶ 943:
(let ((rng (make-rng :mode 'ms :seed 1)))
(dotimes (x 10) (format t "MS: ~d~%" (funcall rng))))</
Another solution could be:
<
(loop for candidate = seed then (mod (+ (* multiplier candidate) adder) bounds)
for result = candidate then (floor (/ candidate divisor))
when (and (< result max) (> result min)) collect result into valid-numbers
when (> (length valid-numbers) times) return result))</
Which defaults to the BSD formula, but can be customized to any formula with keyword arguments, for example:
<
(loop for i from 0 upto 5 collect
(list i
(linear-random 0 :times i)
(linear-random 0 :times i :multiplier 214013 :adder 2531011 :max 32767 :divisor (expt 2 16)))))</
Outputs:
Line 973 ⟶ 970:
=={{header|D}}==
<
enum uint RAND_MAX = (1U << 31) - 1;
uint seed = 0;
Line 1,000 ⟶ 997:
foreach (immutable i; 0 .. 10)
writeln(rnd.randMS);
}</
Output:
<pre>12345
Line 1,027 ⟶ 1,024:
''dc'' has no bitwise operations, so this program uses the modulus operator (<code>2147483648 %</code>) and division (<code>65536 /</code>). Fortunately, ''dc'' numbers cannot overflow to negative, so the modulus calculation involves only non-negative integers.
For BSD rand(): <
* lrx -- (random number from 0 to 2147483647)
*
Line 1,037 ⟶ 1,034:
[* Set seed to 1, then print the first 3 random numbers. *]sz
1 sR
lrx psz lrx psz lrx psz</
<pre>1103527590
Line 1,043 ⟶ 1,040:
662824084</pre>
For Microsoft rand(): <
* lrx -- (random number from 0 to 32767)
*
Line 1,053 ⟶ 1,050:
[* Set seed to 1, then print the first 3 random numbers. *]sz
1 sR
lrx psz lrx psz lrx psz</
<pre>41
Line 1,062 ⟶ 1,059:
{{libheader| Winapi.Windows}}
{{Trans|C#}}
<syntaxhighlight lang="delphi">
program Linear_congruential_generator;
Line 1,135 ⟶ 1,132:
end.
</syntaxhighlight>
{{out}}
Line 1,165 ⟶ 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.
<
[Linear congruential generators for pseudo-random numbers.
EDSAC program, Initial Orders 2.]
Line 1,298 ⟶ 1,338:
E 15 Z [define entry point]
P F [acc = 0 on entry]
</syntaxhighlight>
{{out}}
<pre>
Line 1,327 ⟶ 1,367:
=={{header|Elixir}}==
<
def ms_seed(seed) do
Process.put(:ms_state, seed)
Line 1,361 ⟶ 1,401:
:io.format "~11w~8w~n", [LCG.bsd_rand, LCG.ms_rand]
end)
end)</
{{out}}
Line 1,394 ⟶ 1,434:
=={{header|Erlang}}==
{{trans|Elixir}}
<
-export([bsd_seed/1, ms_seed/1, bsd_rand/0, ms_rand/0]).
Line 1,414 ⟶ 1,454:
ms_seed(0),
io:fwrite("~10s~c~5s~n", ["BSD", 9, "MS"]),
lists:map(fun(_) -> io:fwrite("~10w~c~5w~n", [bsd_rand(),9,ms_rand()]) end, lists:seq(1,10)).</
{{Out}}
Line 1,431 ⟶ 1,471:
=={{header|ERRE}}==
ERRE doesn't generate the proper output from the BSD constants; it uses double-precision floating point, which is not enough for some of the intermediate products: for exact computation you can use MULPREC program. The BSD series deviates starting with the third value (see sample output below).
<
!$DOUBLE
Line 1,464 ⟶ 1,504:
PRINT(TAB(10);XRND)
END FOR
END PROGRAM</
{{out}}
<pre>
Line 1,493 ⟶ 1,533:
=={{header|F_Sharp|F#}}==
<
let bsd seed =
let state = ref seed
Line 1,505 ⟶ 1,545:
state := (214013 * !state + 2531011) &&& System.Int32.MaxValue
!state / (1<<<16))
</syntaxhighlight>
<pre>let rndBSD = lcg.bsd 0;;
let BSD=[for n in [0 .. 9] -> rndBSD()];;
Line 1,520 ⟶ 1,560:
=={{header|Factor}}==
{{works with|Factor|0.98}}
<
: lcg ( seed a c m quot: ( state -- rand ) -- list )
Line 1,527 ⟶ 1,567:
0 1103515245 12345 2147483648 [ ] lcg ! bsd
0 214013 2531011 2147483648 [ -16 shift ] lcg ! ms
[ 10 swap ltake [ . ] leach nl ] bi@</
{{out}}
<pre>
Line 1,554 ⟶ 1,594:
=={{header|Forth}}==
<
1 15 lshift 1- constant MAX-RAND-MS
Line 1,570 ⟶ 1,610:
;
test-random</
Output:
Line 1,589 ⟶ 1,629:
=={{header|Fortran}}==
{{works with|Fortran|90 and later}}
<
implicit none
Line 1,630 ⟶ 1,670:
write(*, "(2i12)") bsdrand(), msrand()
end do
end program</
Output
<pre> BSD MS
Line 1,645 ⟶ 1,685:
=={{header|FreeBASIC}}==
<
' compile with: fbc -s console
Line 1,701 ⟶ 1,741:
Print : Print "hit any key to end program"
Sleep
End</
{{out}}
<pre>MS generator
Line 1,729 ⟶ 1,769:
=={{header|Fōrmulæ}}==
{{FormulaeEntry|page=https://formulae.org/?script=examples/Linear_congruential_generator}}
'''Solution'''
'''Definitions'''
[[File:Fōrmulæ - Linear congruential generator 01.png]]
[[File:Fōrmulæ - Linear congruential generator 02.png]]
'''Test case'''
[[File:Fōrmulæ - Linear congruential generator 03.png]]
[[File:Fōrmulæ - Linear congruential generator 04.png]]
=={{header|Go}}==
<
import "fmt"
Line 1,770 ⟶ 1,820:
example(0)
example(1)
}</
Output:
<pre>
Line 1,791 ⟶ 1,841:
=={{header|Haskell}}==
<
msr = map (`div` 2^16) . tail . iterate (\n -> (214013 * n + 2531011) `mod` 2^31)
main = do
print $ take 10 $ bsd 0 -- can take seeds other than 0, of course
print $ take 10 $ msr 0</
=={{header|Icon}} and {{header|Unicon}}==
The following LCRNG's behave in the same way maintaining the state (seed) from round to round. There is an srand procedure for each lcrng that maintains the seed state and allows the user to assign a new state.
<
procedure main()
Line 1,824 ⟶ 1,874:
procedure rand_MS() #: lcrng
return ishift(srand_MS((214013 * srand_MS() + 2531011) % 2147483648),-16)
end</
{{libheader|Icon Programming Library}}
Line 1,831 ⟶ 1,881:
=={{header|J}}==
'''Solution:'''
<
0 m lcg y NB. default seed of 0
:
Line 1,839 ⟶ 1,889:
rand_bsd=: (1103515245 12345 , <.2^31) lcg
rand_ms=: (2^16) <.@:%~ (214013 2531011 , <.2^31) lcg</
'''Example Use:'''
<
12345 1406932606 654583775 1449466924 229283573 1109335178 1051550459 1293799192 794471793 551188310
654583775 rand_bsd 4
Line 1,848 ⟶ 1,898:
38 7719 21238 2437 8855 11797 8365 32285 10450 30612
1 rand_ms 5 NB. seed of 1
41 18467 6334 26500 19169</
=={{header|Java}}==
{{works with|Java|8}}
<
import static java.util.stream.IntStream.iterate;
Line 1,874 ⟶ 1,924:
.map(i -> i >> 16);
}
}</
<pre>BSD:
Line 1,901 ⟶ 1,951:
=={{header|jq}}==
The Go implementation of jq (gojq) supports unlimited-precision integer arithmetic and therefore linear congruential generators (LCGs) can be trivially written for gojq.
The C implementation of jq, however, currently uses IEEE 754 64-bit numbers for arithmetic, so a BSD generator for the C implementation of jq would require some kind of "big integer" support.
In this entry, therefore, we first present functions for the Microsoft LCG that can be used with jq or gojq, and then present functions to support the BSD generator on the assumption that a suitable "BigInt" library is available.
====Microsoft LCG====
<
# from the Microsoft C Runtime.
# Input: [ count, state, rand ]
Line 1,916 ⟶ 1,970:
| next_rand_Microsoft # the seed is not so random
| recurse(if .[0] < n then next_rand_Microsoft else empty end)
| .[2];</
'''Example''':
rand_Microsoft(1;5)
{{out}}
<
18467
6334
26500
19169</
====BSD LCG====
The following code has been tested with the "BigInt" library at [https://gist.github.com/pkoppstein/d06a123f30c033195841].
<
# Input: [count, previous]
def next_rand_berkeley:
Line 1,940 ⟶ 1,994:
| next_rand_berkeley # skip the seed itself
| recurse(if .[0] < n then next_rand_berkeley else empty end)
| .[1];</
'''Example''':
rand_berkeley(1;5)
{{out}}
<
377401575
662824084
1147902781
2035015474</
=={{header|Julia}}==
<tt>getlgc</tt> creates a linear congruential generator as a closure. This function is used to create the two generators called for by the task.
<
function getlgc(r::Integer, a::Integer, c::Integer, m::Integer, sh::Integer)
Line 1,975 ⟶ 2,029:
for _ in 1:nrep
@printf("%14d\n", msrand())
end</
{{out}}
Line 2,003 ⟶ 2,057:
=={{header|K}}==
<
ms:{1_(y{_(((214013*x)+2531011)!(_2^31))}\x)%(_2^16)}
Line 2,009 ⟶ 2,063:
12345 1406932606 654583775 1449466924 229283573 1109335178 1051550459 1293799192 794471793 551188310
ms[0;10]
38 7719 21238 2437 8855 11797 8365 32285 10450 30612</
=={{header|Kotlin}}==
<
class Lcg(val a: Long, val c: Long, val m: Long, val d: Long, val s: Long) {
Line 2,030 ⟶ 2,084:
val msc = Lcg(214013, 2531011, 1 shl 31, 1 shl 16, 0)
for (i in 1..10) println("${msc.nextInt()}")
}</
{{out}}
Line 2,060 ⟶ 2,114:
=={{header|Liberty BASIC}}==
<syntaxhighlight lang="lb">
'by default these are 0
global BSDState
Line 2,084 ⟶ 2,138:
randMS = int(MSState / 2 ^ 16)
end function
</syntaxhighlight>
=={{header|Logo}}==
Line 2,090 ⟶ 2,144:
Note that, perhaps ironically, [[UCB Logo]], as of version 6.0, doesn't generate the proper output from the BSD constants; it uses double-precision floating point, which is not enough for some of the intermediate products. In UCBLogo, the BSD series deviates starting with the third value (see sample output below).
<
make "LCG_MS [214013 2531011 65536 2147483648]
make "LCG_BSD [1103515245 12345 1 2147483648]
Line 2,119 ⟶ 2,173:
print []
]
bye</
Output:<pre>12345
Line 2,160 ⟶ 2,214:
This requires Lua 5.3 or later because previous versions didn't have support for large integers or integral arithmetic operations.
<
new = function(class, a, c, m, rand)
local self = setmetatable({}, class)
Line 2,186 ⟶ 2,240:
print(("\t%10d"):format(ms.rnd()))
end
</syntaxhighlight>
{{Out}}
Line 2,214 ⟶ 2,268:
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<
NestList[BSDrand, 0, 10]
-> {0, 12345, 1406932606, 654583775, 1449466924, 229283573, 1109335178, 1051550459, 1293799192, 794471793, 551188310}
Line 2,220 ⟶ 2,274:
MSrand[x_] := Mod[x*214013 + 2531011, 2147483648]
BitShiftRight[ NestList[MSrand, 0, 10], 16]
-> {0, 38, 7719, 21238, 2437, 8855, 11797, 8365, 32285, 10450, 30612}</
=={{header|Maxima}}==
<
ms_rand() := quotient(seed: mod(214013 * seed + 2531011, 2147483648), 65536)$
makelist(ms_rand(), 20); /* see http://oeis.org/A096558 */
Line 2,236 ⟶ 2,290:
[12345, 1406932606, 654583775, 1449466924, 229283573, 1109335178, 1051550459,
1293799192, 794471793, 551188310, 803550167, 1772930244, 370913197, 639546082, 1381971571,
1695770928, 2121308585, 1719212846, 996984527, 1157490780]</
=={{header|Nim}}==
<
var state = seed
result = iterator: int =
Line 2,270 ⟶ 2,324:
inc count
if count == 10:
break</
{{out}}
Line 2,296 ⟶ 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,301 ⟶ 2,383:
Function genLCG returns a block object that, when performed, will return the next random number from the LCG.
<
| ch |
Channel newSize(1) dup send(seed) drop ->ch
#[ ch receive a * c + m mod dup ch send drop ] ;</
{{out}}
Line 2,335 ⟶ 2,417:
=={{header|PARI/GP}}==
Note that up to PARI/GP version 2.4.0, <code>random()</code> used a linear congruential generator.
<
MSFTseed=Mod(1,1<<31);
BSD()=BSDseed=1103515245*BSDseed+12345;lift(BSDseed);
MSFT()=MSFTseed=214013*MSFTseed+2531011;lift(MSFTseed)%(1<<31);</
=={{header|Pascal}}==
<
{$mode iso}
var
Line 2,375 ⟶ 2,457:
writeln(bsdrand:12, msrand:12);
end.
</syntaxhighlight>
Output:
<pre> BSD MS
Line 2,390 ⟶ 2,472:
=={{header|Perl}}==
Creates a magic scalar whose value is next in the LCG sequence when read.<
package LCG;
Line 2,429 ⟶ 2,511:
print "\nMS:\n";
print "$rand\n" for 1 .. 10;</
12345
1406932606
Line 2,451 ⟶ 2,533:
32285
10450
30612</
=={{header|Phix}}==
{{libheader|Phix/mpfr}}
As per the comments, I had to resort to gmp to get BSDrnd() to work on 32-bit.
<!--<
<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>
Line 2,490 ⟶ 2,572:
<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>
<!--</
{{out}}
<pre>
Line 2,519 ⟶ 2,601:
=={{header|PHP}}==
{{works with|PHP|5.3+}}
<
function bsd_rand($seed) {
return function() use (&$seed) {
Line 2,543 ⟶ 2,625:
echo $lcg(), " ";
echo "\n";
?></
=={{header|Picat}}==
===Methods as hard coded predicates===
<
% BSD
Line 2,577 ⟶ 2,659:
Seed = cond(M.has_key(ms_state),M.get(ms_state),0),
Rand = ((214013*Seed + 2531011) mod 2**31),
M.put(ms_state,Rand).</
{{out}}
Line 2,587 ⟶ 2,669:
===Generalized version===
Using a global global map for setting/setting seeds etc.
<
% BSD
Line 2,623 ⟶ 2,705:
Rand = ((M.get(multiplier)*M.get(seed) + M.get(adder)) mod M.get(mod)),
M.put(seed,Rand),
get_global_map().put(Type,M).</
{{out}}
Line 2,633 ⟶ 2,715:
=={{header|PicoLisp}}==
<
(de bsdRand ()
Line 2,642 ⟶ 2,724:
(>> 16
(setq *MsSeed
(& (+ 2531011 (* 214013 *MsSeed)) `(dec (** 2 31))) ) ) )</
Output:
<pre>: (do 7 (printsp (bsdRand)))
Line 2,651 ⟶ 2,733:
=={{header|PL/I}}==
<syntaxhighlight lang="text">
(nofixedoverflow, nosize):
LCG: procedure options (main);
Line 2,680 ⟶ 2,762:
end LCG;
</syntaxhighlight>
OUTPUT:
<pre>
Line 2,707 ⟶ 2,789:
=={{header|PowerShell}}==
<
Function msstate{
Param($current_seed)
Line 2,732 ⟶ 2,814:
$seed = randBSD($seed)
Write-Host $seed}
</syntaxhighlight>
{{Out}}
Line 2,751 ⟶ 2,833:
=={{header|PureBasic}}==
<
Static state.q
If seed >= 0
Line 2,787 ⟶ 2,869:
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
CloseConsole()
EndIf</
Sample output:
<pre>BSD (seed = 1)
Line 2,804 ⟶ 2,886:
=={{header|Python}}==
<
def rand():
rand.seed = (1103515245*rand.seed + 12345) & 0x7fffffff
Line 2,816 ⟶ 2,898:
return rand.seed >> 16
rand.seed = seed
return rand</
{{works with|Python|3.x}}
<
def rand():
nonlocal seed
Line 2,830 ⟶ 2,912:
seed = (214013*seed + 2531011) & 0x7fffffff
return seed >> 16
return rand</
=={{header|Quackery}}==
<
10 over size -
space swap of
Line 2,859 ⟶ 2,941:
10 times
[ BSD-rand echonum
MCR-rand echonum cr ]</
{{out}}
Line 2,877 ⟶ 2,959:
=={{header|R}}==
<
rand_BSD <- function(n = 1) {
Line 2,914 ⟶ 2,996:
seed <- 0
rand_MS(10)
## [1] 38 7719 21238 2437 8855 11797 8365 32285 10450 30612</
=={{header|Racket}}==
Line 2,920 ⟶ 3,002:
The following solution uses generators and transcribes the mathematical formulas above directly. It does not attempt to be efficient.
<
#lang racket
(require racket/generator)
Line 2,941 ⟶ 3,023:
(define bsd-rand (rand bsd-update identity))
(define ms-rand (rand ms-update (λ (x) (quotient x (expt 2 16)))))
</syntaxhighlight>
=={{header|Raku}}==
Line 2,948 ⟶ 3,030:
We'll define subroutines implementing the LCG algorithm for each version. We'll make them return a lazy list.
<syntaxhighlight lang="raku"
sub bsd {
$^seed, ( 1103515245 * * + 12345 ) % modulus ... *
Line 2,962 ⟶ 3,044:
say "\nMS LCG first 10 values (first one is the seed):";
.say for ms(0)[^10];</
<pre>BSD LCG first 10 values (first one is the seed):
Line 2,989 ⟶ 3,071:
=={{header|REXX}}==
<
/*──────── 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 3,010 ⟶ 3,092:
" rand" right(ms % two@@16, 6)
end /*j*/
end /*seed*/ /*stick a fork in it, we're all done. */</
{{out|output|text= (shown at five-sixth size.) }}
<pre style="font-size:84%">
Line 3,055 ⟶ 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 3,060 ⟶ 3,164:
You can create multiple instances of LCG::Berkeley or LCG::Microsoft. Each instance privately keeps the original seed in @seed, and the current state in @r. Each class resembles the core Random class, but with fewer features. The .new method takes a seed. The #rand method returns the next random number. The #seed method returns the original seed.
<
module Common
# The original seed of this generator.
Line 3,089 ⟶ 3,193:
end
end
end</
The next example sets the seed to 1, and prints the first 5 random numbers.
<
p (1..5).map {lcg.rand}
# prints [1103527590, 377401575, 662824084, 1147902781, 2035015474]
Line 3,099 ⟶ 3,203:
lcg = LCG::Microsoft.new(1)
p (1..5).map {lcg.rand}
# prints [41, 18467, 6334, 26500, 19169]</
=={{header|Run BASIC}}==
<
global ms
print "Num ___Bsd___";chr$(9);"__Ms_"
Line 3,117 ⟶ 3,221:
ms = (214013 * ms + 2531011) mod (2 ^ 31)
msRnd = int(ms / 2 ^ 16)
end function</
<pre>
Num ___Bsd___ __Ms_
Line 3,132 ⟶ 3,236:
=={{header|Rust}}==
<
pub use rand::{Rng, SeedableRng};
Line 3,202 ⟶ 3,306:
println!("{}", ms.gen::<bool>());
println!("{}", ms.gen_ascii_chars().take(15).collect::<String>());
}</
=={{header|Scala}}==
<
def bsdRandom(rseed:Int):Iterator[Int]=new Iterator[Int]{
var seed=rseed
Line 3,229 ⟶ 3,333:
println("MS : "+ toString( msRandom(1)))
}
}</
{{out}}
<pre>-- seed 0 --
Line 3,248 ⟶ 3,352:
=={{header|Scheme}}==
For R7RS Scheme.
<syntaxhighlight lang="scheme">(import (scheme base)
(scheme write))
(define ((bsd-rand state))
(set! state (remainder (+ (* 1103515245 state) 12345) 2147483648))
state)
(define ((msvcrt-rand state))
(set! state (remainder (+ (* 214013 state) 2531011) 2147483648))
(quotient state 65536))
; auxiliary function to get a list of 'n random numbers from generator 'r
(define (rand-list r n
(if (zero? n) '() (cons (r) (rand-list r (- n 1)))))
(display (rand-list (bsd-rand 0) 10))
; (12345 1406932606 654583775 1449466924 229283573 1109335178 1051550459 1293799192 794471793 551188310)
(newline)
(display (rand-list (msvcrt-rand 0) 10))
; (38 7719 21238 2437 8855 11797 8365 32285 10450 30612)</syntaxhighlight>
=={{header|Seed7}}==
Line 3,271 ⟶ 3,384:
[http://seed7.sourceforge.net/libraries/array.htm#rand%28in_arrayType%29 rand(arr)]. This function selects a random element from an array.
<
include "bigint.s7i";
Line 3,301 ⟶ 3,414:
writeln(bsdRand lpad 12 <& msRand lpad 12);
end for;
end func;</
Output:
Line 3,321 ⟶ 3,434:
Uses the Random library provided by SequenceL to create new Random Number Generators
<syntaxhighlight lang="sequencel">
import <Utilities/Random.sl>;
Line 3,348 ⟶ 3,461:
(Value : newSeed / 65536,
Generator : (Seed : newSeed, RandomMin : RG.RandomMin, RandomMax : RG.RandomMax, NextFunction : RG.NextFunction));
</syntaxhighlight>
Output
<pre>
Line 3,357 ⟶ 3,470:
=={{header|Sidef}}==
{{trans|Ruby}}
<
# Creates a linear congruential generator and remembers the initial seed.
Line 3,386 ⟶ 3,499:
var lcg2 = LCG::Microsoft(1)
say 5.of { lcg2.rand }</
{{out}}
<pre>
Line 3,394 ⟶ 3,507:
=={{header|Sparkling}}==
<
"BSD": 0,
"MS": 0
Line 3,413 ⟶ 3,526:
function Microsoft_rand() {
return (states.MS = (214013 * states.MS + 2531011) % (1 << 31)) % (1 << 15);
}</
Output seen after seeding both generators with 0:
<
spn:9> Microsoft_rand()
= 7875
Line 3,438 ⟶ 3,551:
= 1449466924
spn:19> BSD_rand()
= 229283573</
=={{header|Standard ML}}==
<
open Word32
in
Line 3,452 ⟶ 3,565:
(toInt (>> (state, 0w16)), state)
end
end</
;Test code<nowiki>:</nowiki>
<
(print (" " ^ Int.toString rand); rand)
Line 3,467 ⟶ 3,580:
val () = print "\nMSC:\n"
val () = doTimes (test2 o mscLcg, 7, 0w0)
val () = print "\n"</
{{out}}
<pre>BSD:
Line 3,476 ⟶ 3,589:
=={{header|Stata}}==
<
function rand_bsd(u) {
m = 65536
Line 3,500 ⟶ 3,613:
rand_seq(&rand_bsd(),1,10)
rand_seq(&rand_ms(),0,10)</
'''Output''': compare with OEIS '''[http://oeis.org/A096553 A096553]''' and '''[http://oeis.org/A096558 A096558]'''.
Line 3,535 ⟶ 3,648:
=={{header|Swift}}==
<
class LinearCongruntialGenerator {
Line 3,581 ⟶ 3,694:
{
print(BSDLinearCongruntialGenerator.random())
}</
{{out}}<pre>Microsft Rand:
38
Line 3,608 ⟶ 3,721:
=={{header|Tcl}}==
Using an object-oriented solution, inspired by (but not a translation of) the [[#Ruby|Ruby]] solution above.
<
# General form of a linear-congruential RNG
Line 3,637 ⟶ 3,750:
next $initialSeed 214013 2531011 [expr {2**31}] [expr {2**16}]
}
}</
Demo code:
<
puts BSD:\t\[[sample [BSDRNG new 1]]\]
puts MS:\t\[[sample [MSRNG new 1]]\]</
Output:
<pre>
Line 3,650 ⟶ 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,684 ⟶ 3,797:
m = Pop() % (2 ^ 31) ' Now we got a number less than 2^31
Push m / (2 ^ 16) ' So we can complete the operation
Return</
{{out}}
<pre>BSD
Line 3,715 ⟶ 3,828:
=={{header|UNIX Shell}}==
<
function BSD() {
Line 3,739 ⟶ 3,852:
output BSD
output MS</
{{out}}
Line 3,770 ⟶ 3,883:
=={{header|VBA}}==
<
Public stateMS As Variant
Private Function bsd() As Long
Line 3,795 ⟶ 3,908:
Debug.Print Format(bsd, "@@@@@@@@@@"), Format(ms, "@@@@@")
Next i
End Sub</
<pre> BSD MS
12345 38
Line 3,813 ⟶ 3,926:
{{libheader|Wren-fmt}}
Some of the intermediate calculations here require integers >= 2^53 so we need to use BigInt.
<
import "./fmt" for Fmt
// basic linear congruential generator
Line 3,842 ⟶ 3,955:
example.call(0)
example.call(1)</
{{out}}
Line 3,868 ⟶ 3,981:
First example using integer instructions.
<
;Tested in windows 7 Enterprise Service Pack 1 64 bit
;With the AMD FX(tm)-6300 processor
Line 4,055 ⟶ 4,168:
mov rcx,1
call exit</
Second example using AVX instructions.
{{incorrect|X86 Assembly|It will not produce output identical to that of the Microsoft rand() function.}}
<
;Tested in windows 7 Enterprise Service Pack 1 64 bit
;With the AMD FX(tm)-6300 processor
Line 4,302 ⟶ 4,415:
mov rcx,1
call exit</
{{out|Sample}}
Line 4,364 ⟶ 4,477:
[[File:LCG2XPL0.gif|right]]
<
int R;
Line 4,392 ⟶ 4,505:
N:= ChIn(1); \wait for keystoke
SetVid(3); \restore normal text mode
]</
=={{header|zkl}}==
<
fcn srand(s){ seed = s }
Line 4,408 ⟶ 4,521:
const A=214013, C=2531011, TWO16=(1).shiftLeft(16);
fcn rand{ (seed = (seed * A + C) % TWO31) / TWO16 }
#endif</
<
println(rand(),",",rand(),",",rand());</
{{out}}
<pre>
|