in reply to Old random number generator
As haukex and syphilis already suggested, a good approach is not to depend on Perl's internal RNG algorithm but use your own. Either from one of the modules from CPAN, or roll your own algorithm.
The added benefit, apart from getting same sequences across systems and versions (perhaps with a bit of tuning, re: arithmetic operations overflows etc.) is that you will control the use of this new rand() and you will never miss the next in sequence because another module or part of your program calls rand() too! Imagine if/when that happens conditionally and different runs of your program produce different results because sometimes a rand() is consumed by another part of your program or external module and sometimes it does not.
On this last point (i.e. rand() consumed by system build-in needs) I experimented with build-in hashtable and its random needs - I thought wrongly that it draws from the same system's rand() but this is not true: creating and using a hash in-between 2 rand() calls does not seem change the RNG sequence. I am not sure what other build-ins use RNG, regex engine perhaps?
And now to the juice, as syphilis wonders how one can override a system build-in sub, here is how to override rand() with your own algorithm or calling external module. This will give you seamless behaviour with your existing code and no other changes need to be made to your scripts. Below code also demonstrates (simplistically) how to use different RNGs depending on who is the caller. Here's the codez based on the original solution by LanX:
#!/usr/bin/env perl use strict; use warnings; my $total_sleep_time = 0; BEGIN { *CORE::GLOBAL::rand = sub { my $parent = (caller(1))[3] // ""; if( $parent =~ /abc/ ){ return CORE::rand() } return 123; }; } print "fake rand: ".rand()."\n"; abc(); sub abc { print "real rand(): ".rand()."\n" }
For more information, see the answers to a question I posted here Copy a builtin sub to a different name and then override some time ago.
And if you want the exact same sequence as this version or that platformed produced, then nothing stops you from HARDCODING a random sequence into your programs and use the method above to run through it, instead of using an algorithm. Provided that you will ever going to need just a million r random numbers. (Actually that can become a web-service!)
bw, bliako
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Old random number generator
by syphilis (Archbishop) on May 11, 2020 at 07:45 UTC |