vsespb has asked for the wisdom of the Perl Monks concerning the following question:
I need to get predictible integer random number sequence (for use in unit tests).
Sequence should be strictly same on each run. It does not have to be really random (nor secure random of course)
Seems it's docummented that I can use srand() for this:
perldoc srand:
Questions are:
1. Will this work as expected? On each and every possible perl build and platform?
2. Is there a better way to do it?
Sequence should be strictly same on each run. It does not have to be really random (nor secure random of course)
Seems it's docummented that I can use srand() for this:
perldoc srand:
However, there are a few situations where programs are likely to want to call srand. One is for generating predictable results, generally for testing or debugging. There, you use srand($seed), with the same $seed each time.So I wrote the following code:
prints:use strict; use warnings; use List::Util qw/min/; sub t { sprintf("%0.0f", shift()*10000) } sub rn { my $e = 1e-6; my $x = rand(); return min(t($x), t($x+$e), t($x-$e)); } srand(42654); print rn(), "\n"; print rn(), "\n"; print rn(), "\n"; print rn(), "\n";
I use3725 3516 7534 1948
to get rid of possible float off-by-0.0000...00001 problems.min(t($x), t($x+$e), t($x-$e))
Questions are:
1. Will this work as expected? On each and every possible perl build and platform?
2. Is there a better way to do it?
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: Predictable random sequence
by hdb (Monsignor) on Sep 17, 2013 at 14:14 UTC | |
by vsespb (Chaplain) on Sep 17, 2013 at 14:18 UTC | |
Re: Predictable random sequence
by keszler (Priest) on Sep 17, 2013 at 13:54 UTC | |
by vsespb (Chaplain) on Sep 17, 2013 at 14:04 UTC | |
Re: Predictable random sequence
by Corion (Patriarch) on Sep 17, 2013 at 13:39 UTC | |
by vsespb (Chaplain) on Sep 17, 2013 at 13:41 UTC | |
by Corion (Patriarch) on Sep 17, 2013 at 13:48 UTC | |
Re: Predictable random sequence
by kennethk (Abbot) on Sep 17, 2013 at 14:37 UTC | |
Re: Predictable random sequence
by BrowserUk (Patriarch) on Sep 17, 2013 at 14:36 UTC | |
by vsespb (Chaplain) on Sep 17, 2013 at 14:42 UTC | |
by BrowserUk (Patriarch) on Sep 17, 2013 at 14:49 UTC | |
by vsespb (Chaplain) on Sep 17, 2013 at 15:10 UTC | |
by BrowserUk (Patriarch) on Sep 17, 2013 at 15:32 UTC | |
by BrowserUk (Patriarch) on Sep 17, 2013 at 15:50 UTC | |
| |
by vsespb (Chaplain) on Sep 18, 2013 at 15:38 UTC | |
by BrowserUk (Patriarch) on Sep 18, 2013 at 15:59 UTC | |
Re: Predictable random sequence
by Athanasius (Archbishop) on Sep 17, 2013 at 13:55 UTC | |
by vsespb (Chaplain) on Sep 17, 2013 at 14:06 UTC | |
Re: Predictable random sequence
by Your Mother (Archbishop) on Sep 17, 2013 at 14:42 UTC | |
by Laurent_R (Canon) on Sep 17, 2013 at 16:57 UTC | |
by Anonymous Monk on Sep 17, 2013 at 15:40 UTC |
Back to
Seekers of Perl Wisdom