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:
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:
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";
prints:
3725
3516
7534
1948
I use
min(t($x), t($x+$e), t($x-$e))
to get rid of possible float off-by-0.0000...00001 problems.
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?
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.