Showing pcg32.pl (raw)


  1. #!/usr/bin/env perl
  2.  
  3. ###############################################################################
  4. # Two implementations of PCG32. One in native Perl with no dependencies, and
  5. # one that uses Math::Int64. Surprisingly the native version is significantly
  6. # faster.
  7. #
  8. # A lot of work was done here to mimic how C handles overflow multiplication
  9. # on large uint64_t numbers. Perl converts scalars that are larger than 2^64-1
  10. # to floating point on the backend. We do *NOT* want that for PCG, because
  11. # PCG (and more PRNGs) rely on overflow math to do their magic. We utilize
  12. # 'use integer' to force Perl to do all math with regular 64bit values. When
  13. # overflow occurs Perl likes to convert large values to negative numbers. In
  14. # the original C all math is done with uint64_t, so we have to convert the
  15. # IV/negative numbers back into UV/unsigned (positive) values. PCG also uses
  16. # some uint32_t variables internally, so we mimic that by doing the math in
  17. # 64bit and then masking down to only the 32bit number.
  18. #
  19. ###############################################################################
  20. #
  21. # Original C code from: https://www.pcg-random.org/download.html
  22. #
  23. # typedef struct { uint64_t state;  uint64_t inc; } pcg32_random_t;
  24. #
  25. # uint32_t pcg32_random_r(pcg32_random_t* rng) {
  26. #     uint64_t oldstate = rng->state;
  27. #     // Advance internal state
  28. #     rng->state = oldstate * 6364136223846793005ULL + (rng->inc|1);
  29. #     // Calculate output function (XSH RR), uses old state for max ILP
  30. #     uint32_t xorshifted = ((oldstate >> 18u) ^ oldstate) >> 27u;
  31. #     uint32_t rot = oldstate >> 59u;
  32. #     return (xorshifted >> rot) | (xorshifted << ((-rot) & 31));
  33. # }
  34. #
  35. ###############################################################################
  36.  
  37. use strict;
  38. use warnings;
  39. use v5.16;
  40. use Math::Int64 qw(uint64 uint64_to_number);
  41. use Getopt::Long;
  42. use Test::More;
  43.  
  44. ###############################################################################
  45. ###############################################################################
  46.  
  47. my $debug = 0;
  48. my $s1    = 15939250660798104135; # Default 64bit seed1
  49. my $s2    = 3988331200502121509;  # Default 64bit seed2
  50.  
  51. GetOptions(
  52.     'debug'      => \$debug,
  53.     'seed1=i'    => \$s1,
  54.     'seed2=i'    => \$s2,
  55.     'random'     => \&randomize_seeds,
  56.     'unit-tests' => \&run_unit_tests,
  57. );
  58.  
  59. # We build two sets of seeds from the 32bit seeds
  60. my $seeds64 = [[$s1, 1], [$s2, 1]];
  61. my $seeds32 = [$s1, $s2];
  62.  
  63. my $num = $ARGV[0] || 8;
  64.  
  65. print color('yellow', "Seeding PRNG with: $s1 / $s2\n\n");
  66.  
  67. for (my $i = 1; $i <= $num; $i++) {
  68.     my $num32 = pcg32_perl($seeds32);
  69.     my $num64 = pcg64_perl($seeds64);
  70.     printf("%2d) %10u / %20u\n", $i, $num32, $num64);
  71. }
  72.  
  73. ################################################################################
  74. ################################################################################
  75. ################################################################################
  76.  
  77. #my $seeds = [12, 34];
  78. #my $rand  = pcg32_perl($seeds);
  79. sub pcg32_perl {
  80.     # state/inc are passed in by reference
  81.     my ($seeds)  = @_;
  82.     my $oldstate = $seeds->[0]; # Save original state
  83.  
  84.     # We use interger math because Perl converts to floats any scalar
  85.     # larger than 2^64 - 1. PCG *requires* 64bit uint64_t math, with overflow,
  86.     # to calculate correctly. We have to unconvert the overflowed signed integer (IV)
  87.     # to an unsigned integer (UV) using bitwise or against zero. (weird hack)
  88.     use integer;
  89.     $seeds->[0]  = ($oldstate * 6364136223846793005 + ($seeds->[1] | 1)) | 0;
  90.     no integer;
  91.  
  92.     my $xorshifted = ((($oldstate >> 18) ^ $oldstate) >> 27) & 0xFFFFFFFF;
  93.  
  94.     # -$rot on a uint32_t is the same as (2^32 - $rot)
  95.     my $rot    = ($oldstate >> 59);
  96.     my $invrot = 4294967296 - $rot;
  97.     my $ret    = (($xorshifted >> $rot) | ($xorshifted << ($invrot & 31))) & 0xFFFFFFFF;
  98.  
  99.     if (defined($debug) && $debug > 0) {
  100.         # $oldstate is the state at the start of the function and $inc
  101.         # doesn't change so we can print out the initial values here
  102.         print color('orange', "State : " . ($oldstate | 0) . "/" . ($seeds->[1] | 0) . "\n");
  103.         print color('orange', "State2: " . ($seeds->[0] | 0) . "\n");
  104.         print color('orange', "Xor   : $xorshifted\n");
  105.         print color('orange', "Rot   : $rot\n");
  106.     }
  107.  
  108.     return $ret;
  109. }
  110.  
  111. # Based on the C algorithm: https://chatgpt.com/share/693cc99c-8068-800d-858e-be16ec1d7521
  112. #my $seeds = [12, 34];
  113. #my $rand  = pcg64_perl($seeds);
  114. sub pcg64_perl {
  115.     my $seeds = $_[0];
  116.     my $ret   = (($seeds->[0] >> (($seeds->[0] >> 59) + 5)) ^ $seeds->[0]);
  117.  
  118.     use integer;
  119.     $ret *= 12605985483714917081;
  120.     $seeds->[0] = $seeds->[0] * 6364136223846793005 + $seeds->[1];
  121.     no integer;
  122.  
  123.     $ret = ($ret >> 43) ^ $ret;
  124.  
  125.     return $ret;
  126. }
  127.  
  128. # To get a 64bit number from PCG32 you create two different generators
  129. # and combine the results into a single 64bit value. All the examples
  130. # online show 1 for the inc/seed2 value. I'm not sure why that is, but
  131. # I copied it for my implementation.
  132. #
  133. #my $seeds = [[12, 1], [34,1]];
  134. #my $rand  = pcg64_perl($seeds);
  135. sub pcg64_perl_chained {
  136.     my ($seeds) = @_;
  137.  
  138.     # Get two 32bit ints
  139.     my $high = pcg32_perl($seeds->[0]);
  140.     my $low  = pcg32_perl($seeds->[1]);
  141.  
  142.     # Combine the two 32bits into one 64bit int
  143.     my $ret = ($high << 32) | $low;
  144.  
  145.     return $ret;
  146. }
  147.  
  148. #my $seeds = [uint64(12), uint64(34)];
  149. #my $rand  = pcg32_math64($seeds);
  150. sub pcg32_math64 {
  151.     # state/inc are passed in by reference
  152.     my ($s) = @_;
  153.  
  154.     my $oldstate = $s->[0];
  155.     $s->[0]      = $oldstate * 6364136223846793005 + ($s->[1] | 1);
  156.  
  157.     my $xorshifted = (($oldstate >> 18) ^ $oldstate) >> 27;
  158.     $xorshifted    = $xorshifted & 0xFFFFFFFF; # Convert to uint32_t
  159.  
  160.     my $rot    = $oldstate >> 59;
  161.     my $invrot = 4294967296 - $rot;
  162.  
  163.     my $ret = ($xorshifted >> $rot) | ($xorshifted << ($invrot & 31));
  164.     $ret    = $ret & 0xFFFFFFFF; # Convert to uint32_t
  165.  
  166.     $ret = uint64_to_number($ret);
  167.  
  168.     if ($debug) {
  169.         # $oldstate is the state at the start of the function and $inc
  170.         # doesn't change so we can print out the initial values here
  171.         print color('orange', "State : $oldstate/$s->[1]\n");
  172.         print color('orange', "State2: $s->[0]\n");
  173.         print color('orange', "Xor   : $xorshifted\n");
  174.         print color('orange', "Rot   : $rot\n");
  175.     }
  176.  
  177.     return $ret;
  178. }
  179.  
  180. ###############################################################################
  181. ###############################################################################
  182.  
  183. # String format: '115', '165_bold', '10_on_140', 'reset', 'on_173', 'red', 'white_on_blue'
  184. sub color {
  185.     my ($str, $txt) = @_;
  186.  
  187.     # If we're NOT connected to a an interactive terminal don't do color
  188.     if (-t STDOUT == 0) { return $txt || ""; }
  189.  
  190.     # No string sent in, so we just reset
  191.     if (!length($str) || $str eq 'reset') { return "\e[0m"; }
  192.  
  193.     # Some predefined colors
  194.     my %color_map = qw(red 160 blue 27 green 34 yellow 226 orange 214 purple 93 white 15 black 0);
  195.     $str =~ s|([A-Za-z]+)|$color_map{$1} // $1|eg;
  196.  
  197.     # Get foreground/background and any commands
  198.     my ($fc,$cmd) = $str =~ /^(\d{1,3})?_?(\w+)?$/g;
  199.     my ($bc)      = $str =~ /on_(\d{1,3})$/g;
  200.  
  201.     if (defined($fc) && int($fc) > 255) { $fc = undef; } # above 255 is invalid
  202.  
  203.     # Some predefined commands
  204.     my %cmd_map = qw(bold 1 italic 3 underline 4 blink 5 inverse 7);
  205.     my $cmd_num = $cmd_map{$cmd // 0};
  206.  
  207.     my $ret = '';
  208.     if ($cmd_num)      { $ret .= "\e[${cmd_num}m"; }
  209.     if (defined($fc))  { $ret .= "\e[38;5;${fc}m"; }
  210.     if (defined($bc))  { $ret .= "\e[48;5;${bc}m"; }
  211.     if (defined($txt)) { $ret .= $txt . "\e[0m";   }
  212.  
  213.     return $ret;
  214. }
  215.  
  216. sub randomize_seeds {
  217.     print color(51, "Using random seeds\n");
  218.  
  219.     $s1 = perl_rand64();
  220.     $s2 = perl_rand64();
  221. }
  222.  
  223. sub perl_rand64 {
  224.     my $low  = int(rand() * (2**32-1));
  225.     my $high = int(rand() * (2**32-1));
  226.  
  227.     my $ret = ($high << 32) | $low;
  228.  
  229.     return $ret;
  230. }
  231.  
  232. # Creates methods k() and kd() to print, and print & die respectively
  233. BEGIN {
  234.     if (eval { require Data::Dump::Color }) {
  235.         *k = sub { Data::Dump::Color::dd(@_) };
  236.     } else {
  237.         require Data::Dumper;
  238.         *k = sub { print Data::Dumper::Dumper(\@_) };
  239.     }
  240.  
  241.     sub kd {
  242.         k(@_);
  243.  
  244.         printf("Died at %2\$s line #%3\$s\n",caller());
  245.         exit(15);
  246.     }
  247. }
  248.  
  249. # Run a test with a given seed and return a string of the results
  250. sub quick_test32 {
  251.     my $seed = $_[0];
  252.  
  253.     my @data = ();
  254.     for (my $i = 0; $i < 4; $i++) {
  255.         my $num = pcg32_perl($seed);
  256.         push(@data, $num);
  257.     }
  258.  
  259.     my $ret = join(", ", @data);
  260.     return $ret;
  261. }
  262.  
  263. sub quick_test64 {
  264.     my ($seed) = @_;
  265.  
  266.     my @data = ();
  267.     for (my $i = 0; $i < 4; $i++) {
  268.         my $num = pcg64_perl($seed);
  269.         push(@data, $num);
  270.     }
  271.  
  272.     my $ret = join(", ", @data);
  273.     return $ret;
  274. }
  275.  
  276. sub run_unit_tests {
  277.     # Seeds < 2**32
  278.     cmp_ok(quick_test32([11   , 22])      , 'eq', '0, 1425092920, 3656087653, 1104107026');
  279.     cmp_ok(quick_test32([33   , 44])      , 'eq', '0, 3850707138, 2930351490, 1110209703');
  280.     cmp_ok(quick_test32([55   , 66])      , 'eq', '0, 1725101930, 224698313, 2870828486');
  281.     cmp_ok(quick_test32([12345, 67890])   , 'eq', '0, 8251198, 44679150, 3046830521');
  282.     cmp_ok(quick_test32([9999 , 9999])    , 'eq', '0, 521292032, 3698775557, 199399470');
  283.  
  284.     cmp_ok(quick_test64([[11   , 1], [22   , 1]]), 'eq', '0, 6120727489207695446, 7904312005358798897, 14733674221366828425');
  285.     cmp_ok(quick_test64([[33   , 1], [44   , 1]]), 'eq', '0, 16538661225628040268, 5269891931295187491, 5495286771333204711');
  286.     cmp_ok(quick_test64([[55   , 1], [66   , 1]]), 'eq', '0, 7409256372025208996, 8212781881022671801, 8831782971077082788');
  287.     cmp_ok(quick_test64([[12345, 1], [67890, 1]]), 'eq', '0, 35438628484449140, 42862460907032573, 519456495312580246');
  288.     cmp_ok(quick_test64([[9999 , 1], [9999 , 1]]), 'eq', '0, 2238932229626677504, 14236525402126437484, 10387246122801752400');
  289.  
  290.     # Seeds > 2**32
  291.     cmp_ok(quick_test32([42862460907032573  , 519456495312580246])  , 'eq', '319349001, 562730850, 2229409754, 561058538');
  292.     cmp_ok(quick_test32([6120727489207695446, 7904312005358798897]) , 'eq', '635930912, 2099303707, 1638577555, 1426136496');
  293.     cmp_ok(quick_test32([4841811808465514507, 7141191103728083377]) , 'eq', '1986408540, 4264878569, 3066617590, 731859269');
  294.  
  295.     cmp_ok(quick_test64([[42862460907032573  , 1], [519456495312580246 , 1]]) , 'eq', '1371593519175525487, 17623029558467823369, 17850014000156247978, 768534907509427587');
  296.     cmp_ok(quick_test64([[6120727489207695446, 1], [7904312005358798897, 1]]) , 'eq', '2731302471965979098, 3465889473135782122, 4841811808465514507, 7141191103728083377');
  297.     cmp_ok(quick_test64([[4841811808465514507, 1], [7141191103728083377, 1]]) , 'eq', '8531559717926221063, 6031125200978744796, 3704366926003160989, 5594521440717127703');
  298.  
  299.     done_testing();
  300.     exit(0);
  301. }
  302.  
  303. # vim: tabstop=4 shiftwidth=4 noexpandtab autoindent softtabstop=4