#!/usr/bin/env perl ############################################################################### # Two implementations of PCG32. One in native Perl with no dependencies, and # one that uses Math::Int64. Surprisingly the native version is significantly # faster. # # A lot of work was done here to mimic how C handles overflow multiplication # on large uint64_t numbers. Perl converts scalars that are larger than 2^64-1 # to floating point on the backend. We do *NOT* want that for PCG, because # PCG (and more PRNGs) rely on overflow math to do their magic. We utilize # 'use integer' to force Perl to do all math with regular 64bit values. When # overflow occurs Perl likes to convert those values to negative numbers. In # the original C all math is done with uint64_t, so we have to convert the # IV/negative numbers back into UV/unsigned (positive) values. PCG also uses # some uint32_t variables internally, so we mimic that by doing the math in # 64bit and then masking down to only the 32bit number. # ############################################################################### # # Original C code from: https://www.pcg-random.org/download.html # # typedef struct { uint64_t state; uint64_t inc; } pcg32_random_t; # # uint32_t pcg32_random_r(pcg32_random_t* rng) { # uint64_t oldstate = rng->state; # // Advance internal state # rng->state = oldstate * 6364136223846793005ULL + (rng->inc|1); # // Calculate output function (XSH RR), uses old state for max ILP # uint32_t xorshifted = ((oldstate >> 18u) ^ oldstate) >> 27u; # uint32_t rot = oldstate >> 59u; # return (xorshifted >> rot) | (xorshifted << ((-rot) & 31)); # } # ############################################################################### use strict; use warnings; use v5.16; use Math::Int64 qw(uint64 uint64_to_number); use Getopt::Long; ############################################################################### ############################################################################### my $debug = 0; my $s1 = 15939250660798104135; # Default 64bit seed1 my $s2 = 3988331200502121509; # Default 64bit seed2 GetOptions( 'debug' => \$debug, 'seed1=i' => \$s1, 'seed2=i' => \$s2, ); my $num = $ARGV[0] || 8; my ($seed1, $seed2); print color(83, "Seeding PRNG with: $s1 / $s2\n"); $seed1 = uint64($s1); $seed2 = uint64($s2); my @x = (); for (my $i = 0; $i < $num; $i++) { my $num = pcg32_math64(\$seed1, \$seed2); push(@x, $num); } print color('yellow', "Math::Int64: ") . join(", ", @x); print "\n"; ################################## $seed1 = $s1; $seed2 = $s2; my @y = (); for (my $i = 0; $i < $num; $i++) { my $num = pcg32_native(\$seed1, \$seed2); push(@y, $num); } print color('yellow', "Native Perl: ") . join(", ", @y); print "\n"; ################################## print "\n"; $seed1 = $s1; $seed2 = $s2; my @z = (); for (my $i = 0; $i < $num; $i++) { my $num = pcg64_native(\$seed1, \$seed2); push(@z, $num); } print color('yellow', "Native Perl 64bit: ") . join(", ", @z); print "\n"; ################################################################################ ################################################################################ ################################################################################ #my $seed1 = uint64(11); #my $seed2 = uint64(22); #my $rand = pcg32_native(\$seed1, \$seed2); sub pcg32_math64 { # state/inc are passed in by reference my ($state, $inc) = @_; my $oldstate = $$state; $$state = $oldstate * 6364136223846793005 + ($$inc | 1); my $xorshifted = (($oldstate >> 18) ^ $oldstate) >> 27; $xorshifted = $xorshifted & 0xFFFFFFFF; # Convert to uint32_t my $rot = $oldstate >> 59; my $invrot = 4294967296 - $rot; my $ret = ($xorshifted >> $rot) | ($xorshifted << ($invrot & 31)); $ret = $ret & 0xFFFFFFFF; # Convert to uint32_t $ret = uint64_to_number($ret); if ($debug) { # $oldstate is the state at the start of the function and $inc # doesn't change so we can print out the initial values here print color('orange', "State : $oldstate/$$inc\n"); print color('orange', "State2: $$state\n"); print color('orange', "Xor : $xorshifted\n"); print color('orange', "Rot : $rot\n"); } return $ret; } #my $seed1 = 11; #my $seed2 = 22; #my $rand = pcg32_native(\$seed1, \$seed2); sub pcg32_native { # state/inc are passed in by reference my ($state, $inc) = @_; my $oldstate = $$state; # Save original state # We use interger math because Perl converts to floats any scalar # larger than 2^64. PCG *requires* 64bit uint64_t math, with overflow, # to calculate correctly. We have to unconvert the overflowed number # from an IV to UV after the big math use integer; $$state = $oldstate * 6364136223846793005 + ($$inc | 1); $$state = iv_2_uv($$state); no integer; my $xorshifted = (($oldstate >> 18) ^ $oldstate) >> 27; $xorshifted = $xorshifted & 0xFFFFFFFF; # Convert to uint32_t my $rot = ($oldstate >> 59); # -$rot on a uint32_t is the same as (2^32 - $rot) my $invrot = 4294967296 - $rot; my $ret = ($xorshifted >> $rot) | ($xorshifted << ($invrot & 31)); # Convert to uint32_t $ret = $ret & 0xFFFFFFFF; if ($debug) { # $oldstate is the state at the start of the function and $inc # doesn't change so we can print out the initial values here print color('orange', "State : $oldstate/$$inc\n"); print color('orange', "State2: $$state\n"); print color('orange', "Xor : $xorshifted\n"); print color('orange', "Rot : $rot\n"); } return $ret; } # During large integer math when a UV overflows and wraps back around # Perl casts it as a IV value. For the purposes of PCG we need that # wraparound math to stay in place. We need uint64_t all the time. sub iv_2_uv { my $x = $_[0]; # Flip it from a IV (signed) to a UV (unsigned) # use Devel::Peek; Dump($var) # See the internal Perl type if ($x < 0) { no integer; $x += 18446744073709551615; $x += 1; } return $x; } # To get a 64bit number from PCG32 you create two different generators # and combine the results into a single 64bit value. All the examples # online show 1 for the inc/seed2 value. I'm not sure why that is, but # I copied it for my implementation. # #my $seed1 = 11; #my $seed2 = 22; #my $rand = pcg64_native(\$seed1, \$seed2); sub pcg64_native { my ($s1, $s2) = @_; my $inc = 1; # Can be any 64bit value # $s1 / $s2 are already pointers my $high = pcg32_native($s1, \$inc); my $low = pcg32_native($s2, \$inc); my $ret = ($high << 32) | $low; return $ret; } ############################################################################### ############################################################################### # String format: '115', '165_bold', '10_on_140', 'reset', 'on_173', 'red', 'white_on_blue' sub color { my ($str, $txt) = @_; # If we're NOT connected to a an interactive terminal don't do color if (-t STDOUT == 0) { return $txt || ""; } # No string sent in, so we just reset if (!length($str) || $str eq 'reset') { return "\e[0m"; } # Some predefined colors my %color_map = qw(red 160 blue 27 green 34 yellow 226 orange 214 purple 93 white 15 black 0); $str =~ s|([A-Za-z]+)|$color_map{$1} // $1|eg; # Get foreground/background and any commands my ($fc,$cmd) = $str =~ /^(\d{1,3})?_?(\w+)?$/g; my ($bc) = $str =~ /on_(\d{1,3})$/g; if (defined($fc) && int($fc) > 255) { $fc = undef; } # above 255 is invalid # Some predefined commands my %cmd_map = qw(bold 1 italic 3 underline 4 blink 5 inverse 7); my $cmd_num = $cmd_map{$cmd // 0}; my $ret = ''; if ($cmd_num) { $ret .= "\e[${cmd_num}m"; } if (defined($fc)) { $ret .= "\e[38;5;${fc}m"; } if (defined($bc)) { $ret .= "\e[48;5;${bc}m"; } if (defined($txt)) { $ret .= $txt . "\e[0m"; } return $ret; } # Creates methods k() and kd() to print, and print & die respectively BEGIN { if (eval { require Data::Dump::Color }) { *k = sub { Data::Dump::Color::dd(@_) }; } else { require Data::Dumper; *k = sub { print Data::Dumper::Dumper(\@_) }; } sub kd { k(@_); printf("Died at %2\$s line #%3\$s\n",caller()); exit(15); } } # vim: tabstop=4 shiftwidth=4 noexpandtab autoindent softtabstop=4