http://qs321.pair.com?node_id=501053

Adam has asked for the wisdom of the Perl Monks concerning the following question:

I'm trying to figure out an algorithm for generating a random number that is randomly close to a fixed number such that the results will have a bell curve like distribution. That is, if you ran it thousands of times the answer would be closer to the input most of the time but not all the time. Can anyone help me out with this?


To start you out, here is code to get a smooth distribution (P is short for percentage):
my $pErr = 5; # for plus/minus 5. sub MakeP { my $p = $_[0]; $p -= $pErr; $p += int(rand() * 2 * ($pErr ++ 0.5)); return $p / 100 } #Test my @foo; push @foo, MakeP( 50 ) for 0 .. 20000; @foo = sort @foo; while ( @foo ) { my $next = shift @foo; my $count = 1; while ( @foo and $foo[0] == $next ) { ++$count; shift @foo } printf "%f\t%6d\n", $next, $count; }
Note that the distribution is reasonably smooth... but I want it to clump to the middle in either a bell curve or triangular fashion.

Update

I suppose I could randomly choose the width of the distribution, that clumps things... it is less than elegant though.
sub MakeP { my $p = $_[0]; my $e = 1 + int( rand() * $pErr ); $p -= $e; $p += int( rand() * 2 * ( $e + 0.5 ) ); return $p / 100 }