For a random array element, the important things to check are:
1) Does the element always fall within accepted bounds?
2) Is the distribution properly random?
Best thing to do is set up a wrapper to run your function some large x number of times, then store counts of each element number and print out the counts sorted by element number. This will show distribution and min / max. You can also calculate the average deviation from what would be the best possible distribution. For instance:
use strict;
use warnings;
my $min = 10;
my $max = 100;
my $tests = 10000;
my (%c, $n, $average, $deviations);
for (1..$tests) {
$n = makerandom($min, $max);
$c{$n}++;
}
$average = $tests / ($max - $min + 1);
for (sort {$a <=> $b} keys %c) {
$n = $c{$_};
$deviations += abs($n - $average);
print "$_ => $n\n";
}
print "Average deviation +-" . $deviations / ($max - $min + 1) / $aver
+age * 100 . " % from $tests tests";
sub makerandom {
my ($min, $max) = @_;
return int rand ($max - $min + 1) + $min;
}
As you can see by increasing the number of tests, deviation drops to very little as the number of tests gets very large, therefore the makerandom function is working just fine.
Average deviation +-6.9454945054945 % from 10000 tests
Average deviation +-2.24830769230769 % from 100000 tests
Average deviation +-0.77529010989011 % from 1000000 tests
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|