in reply to Re^2: Old random number generator
in thread Old random number generator

For example, srand 0;print int(rand(99)) for 0..9 must always yield 023647263525973192

This outputs correctly for me:
use warnings; use strict; my_srand(0); print int(my_rand(99)) for 0..9; sub my_srand { use Win32::API; my $srand = Win32::API::More->new( 'msvcrt', 'void srand(unsigned int seed)' ) or die "Error: ".Win32::FormatMessage(Win32::GetLastError()); $srand->Call($_[0]); } sub my_rand { my $rand = Win32::API::More->new( 'msvcrt', 'int rand()' ) or die "Error: ".Win32::FormatMessage(Win32::GetLastError()); return int(($rand->Call()) * $_[0] / 32767); }
It outputs 023647263525973192
The only problem is that it calls my_srand and my_rand, but I gather that the requirement is that it instead call srand and rand.
I don't know how/if the builtin srand and rand can be overridden to point to my_srand and my_rand.

Cheers,
Rob

Replies are listed 'Best First'.
Re^4: Old random number generator
by Pascal666 (Scribe) on May 10, 2020 at 04:45 UTC
    Thank you. I don't mind calling my_srand and my_rand (no need to override srand and rand), but I would prefer a solution that works on Linux as well. The * $_[0] / 32767 part appears to be what I needed. print int(winrand()*99/32767) for 0..9 appears to work beautifully. Thank you everyone for your assistance!
      but I would prefer a solution that works on Linux as well

      On Linux, I'm finding that the behaviour hasn't changed. That is, when I run:
      perl -e 'srand(0); print int(rand(99)) for 0 .. 9'
      on Ubuntu, I get 1674986577768368673 from (current) perl-5.30.0 all the way back to perl-5.6.2.

      Or do you mean that you want the output of the one-liner to also be 023647263525973192 on Linux ?
      That could be tricky ... I'm not sure what that might involve.

      Here's an Inline::C version that does as you want on Windows - but produces a different sequence of numbers (83397779901933762754) on Ubuntu, where RAND_MAX is 2147483647.
      use strict; use warnings; use Inline C => <<'EOC'; SV * max_rand() { return newSViv(RAND_MAX); } void my_srand(int seed) { srand(seed); } SV * my_int_rand(IV limit) { return newSViv(rand() * limit / RAND_MAX); } SV * my_float_rand(IV limit) { return newSVnv((NV)rand() * limit / RAND_MAX); } EOC print "RAND_MAX is: ",max_rand(), "\n"; my_srand(0); print my_int_rand(99) for 0 .. 9; #print int(my_float_rand(99)) for 0 .. 9;
      Annoyingly on Ubuntu, although perl's rand() output seems constant across different versions of perl, it differs from the output of that script.

      Another possibility is that Math::Random might provide the functionality you seek. (I took a quick look, couldn't find anything helpful, and gave up ... but I didn't check it out rigorously.)

      Cheers,
      Rob
Re^4: Old random number generator
by bliako (Abbot) on May 10, 2020 at 09:54 UTC