Showing splitmix64.pl (raw)


  1. #!/usr/bin/env perl
  2.  
  3. use strict;
  4. use warnings;
  5. use v5.16;
  6.  
  7. use Test::More;
  8.  
  9. ###############################################################################
  10. # 2025-01-22: Pure Perl implementation of PRNG splitmix64 PRNG
  11. # Scott Baker / https://www.perturb.org/
  12. ###############################################################################
  13. # A lot of work was done here to mimic how C handles overflow multiplication
  14. # on large uint64_t numbers. Perl converts scalars that are larger than 2^64-1
  15. # to floating point on the backend. We do *NOT* want that, because splitmix
  16. # (and most PRNGs) rely on overflow math to do their magic. We utilize
  17. # 'use integer' to force Perl to do all math with regular 64bit values. When
  18. # overflow occurs Perl likes to convert those values to negative numbers. In
  19. # the original C all math is done with uint64_t, so we have to convert the
  20. # IV/signed numbers back into UV/unsigned (positive) values.
  21. ###############################################################################
  22. #uint64_t splitmix64::rand64() {
  23. #    uint64_t z;
  24. #
  25. #    z = (x += 0x9e3779b97f4a7c15);
  26. #    z = (z ^ (z >> 30)) * 0xbf58476d1ce4e5b9;
  27. #    z = (z ^ (z >> 27)) * 0x94d049bb133111eb;
  28. #
  29. #    return z ^ (z >> 31);
  30. #}
  31. ###############################################################################
  32.  
  33. use Getopt::Long;
  34.  
  35. my $seed        = 11; # Default 64bit seed
  36. my $iters       = 6;
  37. my $random_seed = 0;
  38.  
  39. GetOptions(
  40.     'seed=i'       => \$seed,
  41.     'iterations=i' => \$iters,
  42.     'random_seed'  => \$random_seed,
  43.     'unit-tests'   => \&run_unit_tests,
  44. );
  45.  
  46. if ($random_seed) {
  47.     print color(87, "Using random seed\n");
  48.     $seed = perl_rand64();
  49. }
  50.  
  51. print color(227, "Using seed: $seed\n");
  52.  
  53. my $seed2 = $seed;
  54.  
  55. for my $x (1 .. $iters) {
  56.     my $num1  = splitmix64_perl(\$seed);
  57.     #my $num2  = splitmix64_perl2(\$seed2);
  58.  
  59.     #if ($num1 eq $num2) {  print color('green'); }
  60.     #else { print color('red'); }
  61.  
  62.     printf("%2d: %20u\n", $x, $num1);
  63. }
  64.  
  65. ###############################################################################
  66.  
  67. #my $seed = [10293820198];
  68. #my $num  = splitmix_64_perl($seed);
  69. sub splitmix64_perl {
  70.     # Seed must be passed as a reference so we can update it
  71.     my ($seed) = @_;
  72.  
  73.     use integer;
  74.     my $z  = iv_2_uv($$seed += 11400714819323198485);
  75.     $$seed = iv_2_uv($$seed);
  76.     no integer;
  77.  
  78.     $z = shift_xor_multiply($z, 30, 13787848793156543929);
  79.     $z = shift_xor_multiply($z, 27, 10723151780598845931);
  80.     $z = shift_xor_multiply($z, 31, 1);
  81.  
  82.     return $z;
  83. }
  84.  
  85. # Splitmix does a lot of bitshifting, xoring, and multiplying so we
  86. # create one function to simplify that. We utilize `use integer` to
  87. # make sure all math is done using integers and preserve the rollover
  88. sub shift_xor_multiply {
  89.     my ($x, $shift, $mult) = @_;
  90.  
  91.     # This needs to be done with `no integer`
  92.     no integer;
  93.     $x = ($x ^ ($x >> $shift));
  94.  
  95.     # Use integer math for the overflow
  96.     use integer;
  97.     $x = iv_2_uv($x * $mult);
  98.     no integer;
  99.  
  100.     return $x;
  101. }
  102.  
  103. # During large integer math when a UV overflows and wraps back around
  104. # Perl casts it as a IV value. For the purposes of a PRNG we need that
  105. # wraparound math to stay in place. We need uint64_t all the time.
  106. sub iv_2_uv {
  107.     my $x = $_[0];
  108.  
  109.     # Flip it from a IV (signed) to a UV (unsigned)
  110.     # use Devel::Peek; Dump($var) # See the internal Perl type
  111.     if ($x < 0) {
  112.         no integer;
  113.         $x += 18446744073709551615;
  114.         $x += 1;
  115.     }
  116.  
  117.     return $x;
  118. }
  119.  
  120. ###############################################################################
  121. ###############################################################################
  122.  
  123. sub trim {
  124.     my ($s) = (@_, $_); # Passed in var, or default to $_
  125.     if (!defined($s) || length($s) == 0) { return ""; }
  126.     $s =~ s/^\s*//;
  127.     $s =~ s/\s*$//;
  128.  
  129.     return $s;
  130. }
  131.  
  132. # String format: '115', '165_bold', '10_on_140', 'reset', 'on_173', 'red', 'white_on_blue'
  133. sub color {
  134.     my ($str, $txt) = @_;
  135.  
  136.     # If we're NOT connected to a an interactive terminal don't do color
  137.     if (-t STDOUT == 0) { return $txt || ""; }
  138.  
  139.     # No string sent in, so we just reset
  140.     if (!length($str) || $str eq 'reset') { return "\e[0m"; }
  141.  
  142.     # Some predefined colors
  143.     my %color_map = qw(red 160 blue 27 green 34 yellow 226 orange 214 purple 93 white 15 black 0);
  144.     $str =~ s|([A-Za-z]+)|$color_map{$1} // $1|eg;
  145.  
  146.     # Get foreground/background and any commands
  147.     my ($fc,$cmd) = $str =~ /^(\d{1,3})?_?(\w+)?$/g;
  148.     my ($bc)      = $str =~ /on_(\d{1,3})$/g;
  149.  
  150.     if (defined($fc) && int($fc) > 255) { $fc = undef; } # above 255 is invalid
  151.  
  152.     # Some predefined commands
  153.     my %cmd_map = qw(bold 1 italic 3 underline 4 blink 5 inverse 7);
  154.     my $cmd_num = $cmd_map{$cmd // 0};
  155.  
  156.     my $ret = '';
  157.     if ($cmd_num)      { $ret .= "\e[${cmd_num}m"; }
  158.     if (defined($fc))  { $ret .= "\e[38;5;${fc}m"; }
  159.     if (defined($bc))  { $ret .= "\e[48;5;${bc}m"; }
  160.     if (defined($txt)) { $ret .= $txt . "\e[0m";   }
  161.  
  162.     return $ret;
  163. }
  164.  
  165. # Creates methods k() and kd() to print, and print & die respectively
  166. BEGIN {
  167.     if (eval { require Data::Dump::Color }) {
  168.         *k = sub { Data::Dump::Color::dd(@_) };
  169.     } else {
  170.         require Data::Dumper;
  171.         *k = sub { print Data::Dumper::Dumper(\@_) };
  172.     }
  173.  
  174.     sub kd {
  175.         k(@_);
  176.  
  177.         printf("Died at %2\$s line #%3\$s\n",caller());
  178.         exit(15);
  179.     }
  180. }
  181.  
  182. # Run a test with a given seed and return a string of the results
  183. sub quick_test {
  184.     my $seed = $_[0];
  185.  
  186.     my @data = ();
  187.     for (my $i = 0; $i < 4; $i++) {
  188.         my $num = splitmix64_perl(\$seed);
  189.         push(@data, $num);
  190.     }
  191.  
  192.     my $ret = join(", ", @data);
  193.     return $ret;
  194. }
  195.  
  196. sub run_unit_tests {
  197.     # Seeds < 2**32
  198.     cmp_ok(quick_test(11)       , 'eq', '5833679380957638813, 4839782808629744545, 11769803791402734189, 9308485889748266480');
  199.     cmp_ok(quick_test(22)       , 'eq', '14415425345905102346, 17264975761475716686, 1412077619021228083, 12404402112097020482');
  200.     cmp_ok(quick_test(100)      , 'eq', '2532601429470541124, 269152572843532260, 4491231873834608077, 4673566422923057776');
  201.     cmp_ok(quick_test(123456789), 'eq', '2466975172287755897, 8832083440362974766, 3534771765162737125, 9592110948284743397');
  202.     cmp_ok(quick_test(9999)     , 'eq', '6117204470161645077, 15966700211956150513, 15034308290212886683, 7774926710803868520');
  203.  
  204.     # Seeds > 2**32
  205.     cmp_ok(quick_test(7774926710803868520)  , 'eq', '9605346004387840742, 17435495358832388828, 12684084655726398219, 9795402745067826113');
  206.     cmp_ok(quick_test(9795402745067826113)  , 'eq', '13110559830617540027, 13626988459271143897, 846014752197971904, 13956522239222304255');
  207.     cmp_ok(quick_test(846014752197971904)   , 'eq', '17051223190671778754, 12943043929365758946, 17796463379074244041, 16028253299916138813');
  208.     cmp_ok(quick_test(12943043929365758946) , 'eq', '13152169664619309884, 10188724118650338133, 13259243310153093243, 12185650234802439251');
  209.     cmp_ok(quick_test(16028253299916138813) , 'eq', '17201533047954400773, 3347092783829409799, 2118253649191891459, 15494166571380546778');
  210.  
  211.     done_testing();
  212.     exit(0);
  213. }
  214.  
  215. sub perl_rand64 {
  216.     my $ret = int(rand() * (2**64 - 1));
  217.  
  218.     return $ret;
  219. }
  220.  
  221. # vim: tabstop=4 shiftwidth=4 noexpandtab autoindent softtabstop=4