Pseudo-random numbers/Combined recursive generator MRG32k3a: Difference between revisions

Content added Content deleted
m (→‎{{header|Perl}}: fixed package syntax, as was done with the others in series)
(→‎{{header|Perl}}: proper use of package/class)
Line 246: Line 246:
package MRG32k3a {
package MRG32k3a {


our(@x1,@x2);
use constant {
our $m1 = 2**32 - 209;
m1 => 2**32 - 209,
our $m2 = 2**32 - 22853;
m2 => 2**32 - 22853
};
our @a1 = < 0 1403580 -810728>;
our @a2 = <527612 0 -1370589>;


use Const::Fast;
sub new { @x1 = @x2 = ($_[2], 0, 0) }
const my @a1 => < 0 1403580 -810728>;
const my @a2 => <527612 0 -1370589>;

sub new {
my ($class,undef,$seed) = @_;
my @x1 = my @x2 = ($seed, 0, 0);
bless {x1 => \@x1, x2 => \@x2}, $class;
}


sub next_int {
sub next_int {
my ($class,$self) = @_;
unshift @x1, ($a1[0] * $x1[0] + $a1[1] * $x1[1] + $a1[2] * $x1[2]) % $m1; pop @x1;
unshift @x2, ($a2[0] * $x2[0] + $a2[1] * $x2[1] + $a2[2] * $x2[2]) % $m2; pop @x2;
unshift @{$$self{x1}}, ($a1[0] * $$self{x1}[0] + $a1[1] * $$self{x1}[1] + $a1[2] * $$self{x1}[2]) % m1; pop @{$$self{x1}};
($x1[0] - $x2[0]) % ($m1 + 1)
unshift @{$$self{x2}}, ($a2[0] * $$self{x2}[0] + $a2[1] * $$self{x2}[1] + $a2[2] * $$self{x2}[2]) % m2; pop @{$$self{x2}};
($$self{x1}[0] - $$self{x2}[0]) % (m1 + 1)
}
}


sub next_float { next_int() / ($m1 + 1) }
sub next_float { next_int(@_) / (m1 + 1) }
}
}