⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 ch02_11.htm

📁 By Tom Christiansen and Nathan Torkington ISBN 1-56592-243-3 First Edition, published August 1998
💻 HTM
字号:
<HTML><HEAD><TITLE>Recipe 2.10. Generating Biased Random Numbers (Perl Cookbook)</TITLE><METANAME="DC.title"CONTENT="Perl Cookbook"><METANAME="DC.creator"CONTENT="Tom Christiansen &amp; Nathan Torkington"><METANAME="DC.publisher"CONTENT="O'Reilly &amp; Associates, Inc."><METANAME="DC.date"CONTENT="1999-07-02T01:30:14Z"><METANAME="DC.type"CONTENT="Text.Monograph"><METANAME="DC.format"CONTENT="text/html"SCHEME="MIME"><METANAME="DC.source"CONTENT="1-56592-243-3"SCHEME="ISBN"><METANAME="DC.language"CONTENT="en-US"><METANAME="generator"CONTENT="Jade 1.1/O'Reilly DocBook 3.0 to HTML 4.0"><LINKREV="made"HREF="mailto:online-books@oreilly.com"TITLE="Online Books Comments"><LINKREL="up"HREF="ch02_01.htm"TITLE="2. Numbers"><LINKREL="prev"HREF="ch02_10.htm"TITLE="2.9. Making Numbers Even More Random"><LINKREL="next"HREF="ch02_12.htm"TITLE="2.11. Doing Trigonometry in Degrees, not Radians"></HEAD><BODYBGCOLOR="#FFFFFF"><img alt="Book Home" border="0" src="gifs/smbanner.gif" usemap="#banner-map" /><map name="banner-map"><area shape="rect" coords="1,-2,616,66" href="index.htm" alt="Perl Cookbook"><area shape="rect" coords="629,-11,726,25" href="jobjects/fsearch.htm" alt="Search this book" /></map><div class="navbar"><p><TABLEWIDTH="684"BORDER="0"CELLSPACING="0"CELLPADDING="0"><TR><TDALIGN="LEFT"VALIGN="TOP"WIDTH="228"><ACLASS="sect1"HREF="ch02_10.htm"TITLE="2.9. Making Numbers Even More Random"><IMGSRC="../gifs/txtpreva.gif"ALT="Previous: 2.9. Making Numbers Even More Random"BORDER="0"></A></TD><TDALIGN="CENTER"VALIGN="TOP"WIDTH="228"><B><FONTFACE="ARIEL,HELVETICA,HELV,SANSERIF"SIZE="-1"><ACLASS="chapter"REL="up"HREF="ch02_01.htm"TITLE="2. Numbers"></A></FONT></B></TD><TDALIGN="RIGHT"VALIGN="TOP"WIDTH="228"><ACLASS="sect1"HREF="ch02_12.htm"TITLE="2.11. Doing Trigonometry in Degrees, not Radians"><IMGSRC="../gifs/txtnexta.gif"ALT="Next: 2.11. Doing Trigonometry in Degrees, not Radians"BORDER="0"></A></TD></TR></TABLE></DIV><DIVCLASS="sect1"><H2CLASS="sect1"><ACLASS="title"NAME="ch02-10672">2.10. Generating Biased Random Numbers</A></H2><DIVCLASS="sect2"><H3CLASS="sect2"><ACLASS="title"NAME="ch02-pgfId-653">Problem</A></H3><PCLASS="para"><ACLASS="indexterm"NAME="ch02-idx-1000008047-0"></A><ACLASS="indexterm"NAME="ch02-idx-1000008047-1"></A><ACLASS="indexterm"NAME="ch02-idx-1000008047-2"></A>You want to pick a random value where the probabilities of the values are not equal (the distribution is not even). You might be trying to randomly select a banner to display on a web page, given a set of relative weights saying how often each banner is to be displayed. Alternatively, you might want to simulate behavior according to a normal distribution (the bell curve).</P></DIV><DIVCLASS="sect2"><H3CLASS="sect2"><ACLASS="title"NAME="ch02-pgfId-659">Solution</A></H3><PCLASS="para"><ACLASS="indexterm"NAME="ch02-idx-1000008055-0"></A>If you want a random value distributed according to a specific function  &nbsp;-   e.g., the Gaussian (Normal) distribution  &nbsp;-   consult a statistics textbook to find the appropriate function or algorithm. This subroutine generates random numbers that are normally distributed, with a standard deviation of 1 and a mean of 0.</P><PRECLASS="programlisting">sub gaussian_rand {    my ($u1, $u2);  # uniformly distributed random numbers    my $w;          # variance, then a weight    my ($g1, $g2);  # gaussian-distributed numbers    do {        $u1 = 2 * rand() - 1;        $u2 = 2 * rand() - 1;        $w = $u1*$u1 + $u2*$u2;    } while ( $w &gt;= 1 );    $w = sqrt( (-2 * log($w))  / $w );    $g2 = $u1 * $w;    $g1 = $u2 * $w;    # return both if wanted, else just one    return wantarray ? ($g1, $g2) : $g1;}</PRE><PCLASS="para">If you have a list of weights and values you want to randomly pick from, follow this two-step process: First, turn the weights into a probability distribution with <CODECLASS="literal">weight_to_dist</CODE> below, and then use the distribution to randomly pick a value with <CODECLASS="literal">weighted_rand</CODE>: <ACLASS="indexterm"NAME="ch02-idx-1000008057-0"></A></P><PRECLASS="programlisting"># weight_to_dist: takes a hash mapping key to weight and returns# a hash mapping key to probabilitysub weight_to_dist {    my %weights = @_;    my %dist    = ();    my $total   = 0;    my ($key, $weight);    local $_;    foreach (values %weights) {        $total += $_;    }    while ( ($key, $weight) = each %weights ) {        $dist{$key} = $weight/$total;    }    return %dist;}# weighted_rand: takes a hash mapping key to probability, and# returns the corresponding elementsub weighted_rand {    my %dist = @_;    my ($key, $weight);    while (1) {                     # to avoid floating point inaccuracies        my $rand = rand;        while ( ($key, $weight) = each %dist ) {            return $key if ($rand -= $weight) &lt; 0;        }    }}</PRE></DIV><DIVCLASS="sect2"><H3CLASS="sect2"><ACLASS="title"NAME="ch02-pgfId-767">Discussion</A></H3><PCLASS="para">The <CODECLASS="literal">gaussian_rand</CODE> function implements the <ICLASS="firstterm">polar Box Muller</I> method for turning two independent uniformly distributed random numbers between 0 and 1 (such as <CODECLASS="literal">rand</CODE> returns) into two numbers with a mean of 0 and a standard deviation of 1 (i.e., a Gaussian distribution). To generate numbers with a different mean and standard deviation, multiply the output of <CODECLASS="literal">gaussian_rand</CODE> by the new standard deviation, and then add the new mean:</P><PRECLASS="programlisting"># gaussian_rand as above$mean = 25;$sdev = 2;$salary = gaussian_rand() * $sdev + $mean;printf(&quot;You have been hired at \$%.2f\n&quot;, $salary);</PRE><PCLASS="para">The <CODECLASS="literal">weighted_rand</CODE><ACLASS="indexterm"NAME="ch02-idx-1000008049-0"></A><ACLASS="indexterm"NAME="ch02-idx-1000008049-1"></A> function picks a random number between 0 and 1. It then uses the probabilities generated by <CODECLASS="literal">weight_to_dist</CODE> to see which element the random number corresponds to. Because of the vagaries of floating-point representation, the accumulated errors of representation might mean we don't find an element to return. This is why we wrap the code in a <CODECLASS="literal">while</CODE> to pick a new random number and try again.</P><PCLASS="para">In addition, the CPAN module Math::Random has functions to return random numbers from a variety of distributions.</P></DIV><DIVCLASS="sect2"><H3CLASS="sect2"><ACLASS="title"NAME="ch02-pgfId-787">See Also</A></H3><PCLASS="para">The <CODECLASS="literal">rand</CODE> function in <EMCLASS="emphasis">perlfunc</EM> (1) and <ACLASS="olink"HREF="../prog/ch03_01.htm">Chapter 3</A> of <ACLASS="citetitle"HREF="../prog/index.htm"TITLE="Programming Perl"><CITECLASS="citetitle">Programming Perl</CITE></A>; <ACLASS="xref"HREF="ch02_08.htm"TITLE="Generating Random Numbers">Recipe 2.7</A>; the documentation for the CPAN module Math::Random <ACLASS="indexterm"NAME="ch02-idx-1000008051-0"></A><ACLASS="indexterm"NAME="ch02-idx-1000008051-1"></A><ACLASS="indexterm"NAME="ch02-idx-1000008051-2"></A><ACLASS="indexterm"NAME="ch02-idx-1000008051-3"></A><ACLASS="indexterm"NAME="ch02-idx-1000008051-4"></A></P></DIV></DIV><DIVCLASS="htmlnav"><P></P><HRALIGN="LEFT"WIDTH="684"TITLE="footer"><TABLEWIDTH="684"BORDER="0"CELLSPACING="0"CELLPADDING="0"><TR><TDALIGN="LEFT"VALIGN="TOP"WIDTH="228"><ACLASS="sect1"HREF="ch02_10.htm"TITLE="2.9. Making Numbers Even More Random"><IMGSRC="../gifs/txtpreva.gif"ALT="Previous: 2.9. Making Numbers Even More Random"BORDER="0"></A></TD><TDALIGN="CENTER"VALIGN="TOP"WIDTH="228"><ACLASS="book"HREF="index.htm"TITLE="Perl Cookbook"><IMGSRC="../gifs/txthome.gif"ALT="Perl Cookbook"BORDER="0"></A></TD><TDALIGN="RIGHT"VALIGN="TOP"WIDTH="228"><ACLASS="sect1"HREF="ch02_12.htm"TITLE="2.11. Doing Trigonometry in Degrees, not Radians"><IMGSRC="../gifs/txtnexta.gif"ALT="Next: 2.11. Doing Trigonometry in Degrees, not Radians"BORDER="0"></A></TD></TR><TR><TDALIGN="LEFT"VALIGN="TOP"WIDTH="228">2.9. Making Numbers Even More Random</TD><TDALIGN="CENTER"VALIGN="TOP"WIDTH="228"><ACLASS="index"HREF="index/index.htm"TITLE="Book Index"><IMGSRC="../gifs/index.gif"ALT="Book Index"BORDER="0"></A></TD><TDALIGN="RIGHT"VALIGN="TOP"WIDTH="228">2.11. Doing Trigonometry in Degrees, not Radians</TD></TR></TABLE><HRALIGN="LEFT"WIDTH="684"TITLE="footer"><FONTSIZE="-1"></DIV<!-- LIBRARY NAV BAR --> <img src="../gifs/smnavbar.gif" usemap="#library-map" border="0" alt="Library Navigation Links"><p> <a href="copyrght.htm">Copyright &copy; 2002</a> O'Reilly &amp; Associates. All rights reserved.</font> </p> <map name="library-map"> <area shape="rect" coords="1,0,85,94" href="../index.htm"><area shape="rect" coords="86,1,178,103" href="../lwp/index.htm"><area shape="rect" coords="180,0,265,103" href="../lperl/index.htm"><area shape="rect" coords="267,0,353,105" href="../perlnut/index.htm"><area shape="rect" coords="354,1,446,115" href="../prog/index.htm"><area shape="rect" coords="448,0,526,132" href="../tk/index.htm"><area shape="rect" coords="528,1,615,119" href="../cookbook/index.htm"><area shape="rect" coords="617,0,690,135" href="../pxml/index.htm"></map> </BODY></HTML>

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -