Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??
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 }

In reply to Curved Random Distribution by Adam

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":



  • 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.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others admiring the Monastery: (3)
As of 2024-04-25 23:36 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found