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):
Update
I suppose I could randomly choose the width of the distribution, that clumps things... it is less than elegant though.
To start you out, here is code to get a smooth distribution (P is short for percentage):
Note that the distribution is reasonably smooth... but I want it to clump to the middle in either a bell curve or triangular fashion.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; }
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 }
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: Curved Random Distribution
by fglock (Vicar) on Oct 18, 2005 at 16:33 UTC | |
by xdg (Monsignor) on Oct 18, 2005 at 17:50 UTC | |
Re: Curved Random Distribution
by Limbic~Region (Chancellor) on Oct 18, 2005 at 16:55 UTC | |
Re: Curved Random Distribution
by BrowserUk (Patriarch) on Oct 18, 2005 at 17:27 UTC | |
by Roy Johnson (Monsignor) on Oct 18, 2005 at 17:45 UTC | |
by BrowserUk (Patriarch) on Oct 18, 2005 at 20:01 UTC | |
Re: Curved Random Distribution
by blokhead (Monsignor) on Oct 18, 2005 at 17:08 UTC |
Back to
Seekers of Perl Wisdom