Linear congruential generator: Difference between revisions

→‎Tcl: Added implementation
(→‎Tcl: Added implementation)
Line 277:
p (1..5).map {lcg.rand}
# prints [41, 18467, 6334, 26500, 19169]</lang>
 
=={{header|Tcl}}==
<lang tcl>package require Tcl 8.6
 
# General form of a linear-congruential RNG
oo::class create LCRNG {
variable seed A B C D
constructor {init a b c d} {
if {$init < 1} {set init [clock clicks]}
variable seed $init A $a B $b C $c D $d
}
method rand {} {
set seed [expr {($A * $seed + $B) % $C}]
return [expr {$seed / $D}]
}
method srand x {
set seed $x
}
}
# Subclass to introduce constants
oo::class create BSDRNG {
superclass LCRNG
constructor {{initialSeed -1}} {
next $initialSeed 1103515245 12345 [expr {2**31}] 1
}
}
oo::class create MSRNG {
superclass LCRNG
constructor {{initialSeed -1}} {
next $initialSeed 214013 2531011 [expr {2**31}] [expr {2**16}]
}
}</lang>
Demo code:
<lang tcl>proc sample rng {foreach - {1 2 3 4 5} {lappend r [$rng rand]}; join $r ", "}
puts BSD:\[[sample [BSDRNG new 1]]\]
puts MS:\[[sample [MSRNG new 1]]\]</lang>
Output:
<pre>
BSD:[1103527590, 377401575, 662824084, 1147902781, 2035015474]
MS:[41, 18467, 6334, 26500, 19169]
</pre>
Anonymous user