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

📄 randomvar.html

📁 Shall高级编程
💻 HTML
📖 第 1 页 / 共 3 页
字号:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><HTML><HEAD><TITLE>$RANDOM: generate random integer</TITLE><METANAME="GENERATOR"CONTENT="Modular DocBook HTML Stylesheet Version 1.76b+"><LINKREL="HOME"TITLE="Advanced Bash-Scripting Guide"HREF="index.html"><LINKREL="UP"TITLE="Variables Revisited"HREF="variables2.html"><LINKREL="PREVIOUS"TITLE="Indirect References"HREF="ivr.html"><LINKREL="NEXT"TITLE="The Double Parentheses Construct"HREF="dblparens.html"><METAHTTP-EQUIV="Content-Style-Type"CONTENT="text/css"><LINKREL="stylesheet"HREF="common/kde-common.css"TYPE="text/css"><METAHTTP-EQUIV="Content-Type"CONTENT="text/html; charset=iso-8859-1"><METAHTTP-EQUIV="Content-Language"CONTENT="en"><LINKREL="stylesheet"HREF="common/kde-localised.css"TYPE="text/css"TITLE="KDE-English"><LINKREL="stylesheet"HREF="common/kde-default.css"TYPE="text/css"TITLE="KDE-Default"></HEAD><BODYCLASS="SECT1"BGCOLOR="#FFFFFF"TEXT="#000000"LINK="#AA0000"VLINK="#AA0055"ALINK="#AA0000"STYLE="font-family: sans-serif;"><DIVCLASS="NAVHEADER"><TABLESUMMARY="Header navigation table"WIDTH="100%"BORDER="0"CELLPADDING="0"CELLSPACING="0"><TR><THCOLSPAN="3"ALIGN="center">Advanced Bash-Scripting Guide: An in-depth exploration of the art of shell scripting</TH></TR><TR><TDWIDTH="10%"ALIGN="left"VALIGN="bottom"><AHREF="ivr.html"ACCESSKEY="P">Prev</A></TD><TDWIDTH="80%"ALIGN="center"VALIGN="bottom">Chapter 9. Variables Revisited</TD><TDWIDTH="10%"ALIGN="right"VALIGN="bottom"><AHREF="dblparens.html"ACCESSKEY="N">Next</A></TD></TR></TABLE><HRALIGN="LEFT"WIDTH="100%"></DIV><DIVCLASS="SECT1"><H1CLASS="SECT1"><ANAME="RANDOMVAR"></A>9.6. $RANDOM: generate random integer</H1><P><ANAME="RANDOMVAR01"></A></P><P><TTCLASS="VARNAME">$RANDOM</TT> is an internal Bash <AHREF="functions.html#FUNCTIONREF">function</A> (not a constant) that	  returns a <ICLASS="FIRSTTERM">pseudorandom</I>	    <ANAME="AEN5704"HREF="#FTN.AEN5704">[1]</A>	  integer in the range 0 - 32767. It should	  <TTCLASS="REPLACEABLE"><I>not</I></TT> be used to generate an encryption	  key.</P><DIVCLASS="EXAMPLE"><HR><ANAME="EX21"></A><P><B>Example 9-26. Generating random numbers</B></P><TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="100%"><TR><TD><PRECLASS="PROGRAMLISTING">   1&nbsp;#!/bin/bash   2&nbsp;   3&nbsp;# $RANDOM returns a different random integer at each invocation.   4&nbsp;# Nominal range: 0 - 32767 (signed 16-bit integer).   5&nbsp;   6&nbsp;MAXCOUNT=10   7&nbsp;count=1   8&nbsp;   9&nbsp;echo  10&nbsp;echo "$MAXCOUNT random numbers:"  11&nbsp;echo "-----------------"  12&nbsp;while [ "$count" -le $MAXCOUNT ]      # Generate 10 ($MAXCOUNT) random integers.  13&nbsp;do  14&nbsp;  number=$RANDOM  15&nbsp;  echo $number  16&nbsp;  let "count += 1"  # Increment count.  17&nbsp;done  18&nbsp;echo "-----------------"  19&nbsp;  20&nbsp;# If you need a random int within a certain range, use the 'modulo' operator.  21&nbsp;# This returns the remainder of a division operation.  22&nbsp;  23&nbsp;RANGE=500  24&nbsp;  25&nbsp;echo  26&nbsp;  27&nbsp;number=$RANDOM  28&nbsp;let "number %= $RANGE"  29&nbsp;#           ^^  30&nbsp;echo "Random number less than $RANGE  ---  $number"  31&nbsp;  32&nbsp;echo  33&nbsp;  34&nbsp;  35&nbsp;  36&nbsp;#  If you need a random integer greater than a lower bound,  37&nbsp;#+ then set up a test to discard all numbers below that.  38&nbsp;  39&nbsp;FLOOR=200  40&nbsp;  41&nbsp;number=0   #initialize  42&nbsp;while [ "$number" -le $FLOOR ]  43&nbsp;do  44&nbsp;  number=$RANDOM  45&nbsp;done  46&nbsp;echo "Random number greater than $FLOOR ---  $number"  47&nbsp;echo  48&nbsp;  49&nbsp;   # Let's examine a simple alternative to the above loop, namely  50&nbsp;   #       let "number = $RANDOM + $FLOOR"  51&nbsp;   # That would eliminate the while-loop and run faster.  52&nbsp;   # But, there might be a problem with that. What is it?  53&nbsp;  54&nbsp;  55&nbsp;  56&nbsp;# Combine above two techniques to retrieve random number between two limits.  57&nbsp;number=0   #initialize  58&nbsp;while [ "$number" -le $FLOOR ]  59&nbsp;do  60&nbsp;  number=$RANDOM  61&nbsp;  let "number %= $RANGE"  # Scales $number down within $RANGE.  62&nbsp;done  63&nbsp;echo "Random number between $FLOOR and $RANGE ---  $number"  64&nbsp;echo  65&nbsp;  66&nbsp;  67&nbsp;  68&nbsp;# Generate binary choice, that is, "true" or "false" value.  69&nbsp;BINARY=2  70&nbsp;T=1  71&nbsp;number=$RANDOM  72&nbsp;  73&nbsp;let "number %= $BINARY"  74&nbsp;#  Note that    let "number &#62;&#62;= 14"    gives a better random distribution  75&nbsp;#+ (right shifts out everything except last binary digit).  76&nbsp;if [ "$number" -eq $T ]  77&nbsp;then  78&nbsp;  echo "TRUE"  79&nbsp;else  80&nbsp;  echo "FALSE"  81&nbsp;fi    82&nbsp;  83&nbsp;echo  84&nbsp;  85&nbsp;  86&nbsp;# Generate a toss of the dice.  87&nbsp;SPOTS=6   # Modulo 6 gives range 0 - 5.  88&nbsp;          # Incrementing by 1 gives desired range of 1 - 6.  89&nbsp;          # Thanks, Paulo Marcel Coelho Aragao, for the simplification.  90&nbsp;die1=0  91&nbsp;die2=0  92&nbsp;# Would it be better to just set SPOTS=7 and not add 1? Why or why not?  93&nbsp;  94&nbsp;# Tosses each die separately, and so gives correct odds.  95&nbsp;  96&nbsp;    let "die1 = $RANDOM % $SPOTS +1" # Roll first one.  97&nbsp;    let "die2 = $RANDOM % $SPOTS +1" # Roll second one.  98&nbsp;    #  Which arithmetic operation, above, has greater precedence --  99&nbsp;    #+ modulo (%) or addition (+)? 100&nbsp; 101&nbsp; 102&nbsp;let "throw = $die1 + $die2" 103&nbsp;echo "Throw of the dice = $throw" 104&nbsp;echo 105&nbsp; 106&nbsp; 107&nbsp;exit 0</PRE></TD></TR></TABLE><HR></DIV><DIVCLASS="EXAMPLE"><HR><ANAME="PICKCARD"></A><P><B>Example 9-27. Picking a random card from a deck</B></P><TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="100%"><TR><TD><PRECLASS="PROGRAMLISTING">   1&nbsp;#!/bin/bash   2&nbsp;# pick-card.sh   3&nbsp;   4&nbsp;# This is an example of choosing random elements of an array.   5&nbsp;   6&nbsp;   7&nbsp;# Pick a card, any card.   8&nbsp;   9&nbsp;Suites="Clubs  10&nbsp;Diamonds  11&nbsp;Hearts  12&nbsp;Spades"  13&nbsp;  14&nbsp;Denominations="2  15&nbsp;3  16&nbsp;4  17&nbsp;5  18&nbsp;6  19&nbsp;7  20&nbsp;8  21&nbsp;9  22&nbsp;10  23&nbsp;Jack  24&nbsp;Queen  25&nbsp;King  26&nbsp;Ace"  27&nbsp;  28&nbsp;# Note variables spread over multiple lines.  29&nbsp;  30&nbsp;  31&nbsp;suite=($Suites)                # Read into array variable.  32&nbsp;denomination=($Denominations)  33&nbsp;  34&nbsp;num_suites=${#suite[*]}        # Count how many elements.  35&nbsp;num_denominations=${#denomination[*]}  36&nbsp;  37&nbsp;echo -n "${denomination[$((RANDOM%num_denominations))]} of "  38&nbsp;echo ${suite[$((RANDOM%num_suites))]}  39&nbsp;  40&nbsp;  41&nbsp;# $bozo sh pick-cards.sh  42&nbsp;# Jack of Clubs  43&nbsp;  44&nbsp;  45&nbsp;# Thank you, "jipe," for pointing out this use of $RANDOM.  46&nbsp;exit 0</PRE></TD></TR></TABLE><HR></DIV><P><ANAME="BROWNIANREF"></A></P><DIVCLASS="EXAMPLE"><HR><ANAME="BROWNIAN"></A><P><B>Example 9-28. Brownian Motion Simulation</B></P><TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="100%"><TR><TD><PRECLASS="PROGRAMLISTING">   1&nbsp;#!/bin/bash   2&nbsp;# brownian.sh   3&nbsp;# Author: Mendel Cooper   4&nbsp;# Reldate: 10/26/07   5&nbsp;# License: GPL3   6&nbsp;   7&nbsp;#  ----------------------------------------------------------------   8&nbsp;#  This script models Brownian motion:   9&nbsp;#+ the random wanderings of tiny particles in a fluid,  10&nbsp;#+ as they are buffeted by random currents and collisions.  11&nbsp;#+ This is colloquially known as the "Drunkard's Walk."  12&nbsp;  13&nbsp;#  It can also be considered as a stripped-down simulation of a  14&nbsp;#+ Galton Board, a slanted board with a pattern of pegs,  15&nbsp;#+ down which rolls a succession of marbles, one at a time.  16&nbsp;#+ At the bottom is a row of slots or catch basins in which  17&nbsp;#+ the marbles come to rest at the end of their journey.  18&nbsp;#  Think of it as a kind of bare-bones Pachinko game.  19&nbsp;#  As you see by running the script,  20&nbsp;#+ most of the marbles cluster around the center slot.  21&nbsp;#+ This is consistent with the expected binomial distribution.  22&nbsp;#  As a Galton Board simulation, the script  23&nbsp;#+ disregards such parameters as  24&nbsp;#+ board tilt-angle, rolling friction of the marbles,  25&nbsp;#+ angles of impact, and elasticity of the pegs.  26&nbsp;#  How does this affect the accuracy of the simulation?  27&nbsp;#  ----------------------------------------------------------------  28&nbsp;  29&nbsp;PASSES=500            # Number of particle interactions / marbles.  30&nbsp;ROWS=10               # Number of "collisions" (or horiz. peg rows).  31&nbsp;RANGE=3               # 0 - 2 output range from $RANDOM.  32&nbsp;POS=0                 # Left/right position.  33&nbsp;  34&nbsp;declare -a Slots      # Array holding cumulative results of passes.  35&nbsp;NUMSLOTS=21           # Number of slots at bottom of board.  36&nbsp;  37&nbsp;  38&nbsp;Initialize_Slots () { # Zero out all elements of array.  39&nbsp;for i in $( seq $NUMSLOTS )  40&nbsp;do  41&nbsp;  Slots[$i]=0  42&nbsp;done  43&nbsp;  44&nbsp;echo                  # Blank line at beginning of run.  45&nbsp;  }  46&nbsp;  47&nbsp;  48&nbsp;Show_Slots () {  49&nbsp;echo -n " "  50&nbsp;for i in $( seq $NUMSLOTS )   # Pretty-print array elements.  51&nbsp;do  52&nbsp;  printf "%3d" ${Slots[$i]}   # Three spaces per result.  53&nbsp;done  54&nbsp;  55&nbsp;echo # Row of slots:  56&nbsp;echo " |__|__|__|__|__|__|__|__|__|__|__|__|__|__|__|__|__|__|__|__|__|"  57&nbsp;echo "                                ^^"  58&nbsp;echo #  Note that if the count within any particular slot exceeds 99,  59&nbsp;     #+ it messes up the display.  60&nbsp;     #  Running only(!) 500 passes usually avoids this.  61&nbsp;  }  62&nbsp;  63&nbsp;  64&nbsp;Move () {              # Move one unit right / left, or stay put.  65&nbsp;  Move=$RANDOM         # How random is $RANDOM? Well, let's see ...  66&nbsp;  let "Move %= RANGE"  # Normalize into range of 0 - 2.  67&nbsp;  case "$Move" in  68&nbsp;    0 ) ;;                   # Do nothing, i.e., stay in place.  69&nbsp;    1 ) ((POS--));;          # Left.  70&nbsp;    2 ) ((POS++));;          # Right.  71&nbsp;    * ) echo -n "Error ";;   # Anomaly! (Should never occur.)  72&nbsp;  esac

⌨️ 快捷键说明

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