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

📄 mathc.html

📁 Shall高级编程
💻 HTML
📖 第 1 页 / 共 2 页
字号:
> using a <ICLASS="FIRSTTERM">here	        document</I></B></P><TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="90%"><TR><TD><PRECLASS="PROGRAMLISTING">   1&nbsp;#!/bin/bash   2&nbsp;# Invoking 'bc' using command substitution   3&nbsp;# in combination with a 'here document'.   4&nbsp;   5&nbsp;   6&nbsp;var1=`bc &#60;&#60; EOF   7&nbsp;18.33 * 19.78   8&nbsp;EOF   9&nbsp;`  10&nbsp;echo $var1       # 362.56  11&nbsp;  12&nbsp;  13&nbsp;#  $( ... ) notation also works.  14&nbsp;v1=23.53  15&nbsp;v2=17.881  16&nbsp;v3=83.501  17&nbsp;v4=171.63  18&nbsp;  19&nbsp;var2=$(bc &#60;&#60; EOF  20&nbsp;scale = 4  21&nbsp;a = ( $v1 + $v2 )  22&nbsp;b = ( $v3 * $v4 )  23&nbsp;a * b + 15.35  24&nbsp;EOF  25&nbsp;)  26&nbsp;echo $var2       # 593487.8452  27&nbsp;  28&nbsp;  29&nbsp;var3=$(bc -l &#60;&#60; EOF  30&nbsp;scale = 9  31&nbsp;s ( 1.7 )  32&nbsp;EOF  33&nbsp;)  34&nbsp;# Returns the sine of 1.7 radians.  35&nbsp;# The "-l" option calls the 'bc' math library.  36&nbsp;echo $var3       # .991664810  37&nbsp;  38&nbsp;  39&nbsp;# Now, try it in a function...  40&nbsp;hypotenuse ()    # Calculate hypotenuse of a right triangle.  41&nbsp;{                # c = sqrt( a^2 + b^2 )  42&nbsp;hyp=$(bc -l &#60;&#60; EOF  43&nbsp;scale = 9  44&nbsp;sqrt ( $1 * $1 + $2 * $2 )  45&nbsp;EOF  46&nbsp;)  47&nbsp;# Can't directly return floating point values from a Bash function.  48&nbsp;# But, can echo-and-capture:  49&nbsp;echo "$hyp"  50&nbsp;}  51&nbsp;  52&nbsp;hyp=$(hypotenuse 3.68 7.31)  53&nbsp;echo "hypotenuse = $hyp"    # 8.184039344  54&nbsp;  55&nbsp;  56&nbsp;exit 0</PRE></TD></TR></TABLE><HR></DIV><P><ANAME="CANNONREF"></A></P><DIVCLASS="EXAMPLE"><HR><ANAME="CANNON"></A><P><B>Example 15-48. Calculating PI</B></P><TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="90%"><TR><TD><PRECLASS="PROGRAMLISTING">   1&nbsp;#!/bin/bash   2&nbsp;# cannon.sh: Approximating PI by firing cannonballs.   3&nbsp;   4&nbsp;# This is a very simple instance of a "Monte Carlo" simulation:   5&nbsp;#+ a mathematical model of a real-life event,   6&nbsp;#+ using pseudorandom numbers to emulate random chance.   7&nbsp;   8&nbsp;#  Consider a perfectly square plot of land, 10000 units on a side.   9&nbsp;#  This land has a perfectly circular lake in its center,  10&nbsp;#+ with a diameter of 10000 units.  11&nbsp;#  The plot is actually mostly water, except for land in the four corners.  12&nbsp;#  (Think of it as a square with an inscribed circle.)  13&nbsp;#  14&nbsp;#  We will fire iron cannonballs from an old-style cannon  15&nbsp;#+ at the square.  16&nbsp;#  All the shots impact somewhere on the square,  17&nbsp;#+ either in the lake or on the dry corners.  18&nbsp;#  Since the lake takes up most of the area,  19&nbsp;#+ most of the shots will SPLASH! into the water.  20&nbsp;#  Just a few shots will THUD! into solid ground  21&nbsp;#+ in the four corners of the square.  22&nbsp;#  23&nbsp;#  If we take enough random, unaimed shots at the square,  24&nbsp;#+ Then the ratio of SPLASHES to total shots will approximate  25&nbsp;#+ the value of PI/4.  26&nbsp;#  27&nbsp;#  The reason for this is that the cannon is actually shooting  28&nbsp;#+ only at the upper right-hand quadrant of the square,  29&nbsp;#+ i.e., Quadrant I of the Cartesian coordinate plane.  30&nbsp;#  (The previous explanation was a simplification.)  31&nbsp;#  32&nbsp;#  Theoretically, the more shots taken, the better the fit.  33&nbsp;#  However, a shell script, as opposed to a compiled language  34&nbsp;#+ with floating-point math built in, requires a few compromises.  35&nbsp;#  This tends to lower the accuracy of the simulation, of course.  36&nbsp;  37&nbsp;  38&nbsp;DIMENSION=10000  # Length of each side of the plot.  39&nbsp;                 # Also sets ceiling for random integers generated.  40&nbsp;  41&nbsp;MAXSHOTS=1000    # Fire this many shots.  42&nbsp;                 # 10000 or more would be better, but would take too long.  43&nbsp;PMULTIPLIER=4.0  # Scaling factor to approximate PI.  44&nbsp;  45&nbsp;get_random ()  46&nbsp;{  47&nbsp;SEED=$(head -n 1 /dev/urandom | od -N 1 | awk '{ print $2 }')  48&nbsp;RANDOM=$SEED                                  #  From "seeding-random.sh"  49&nbsp;                                              #+ example script.  50&nbsp;let "rnum = $RANDOM % $DIMENSION"             #  Range less than 10000.  51&nbsp;echo $rnum  52&nbsp;}  53&nbsp;  54&nbsp;distance=        # Declare global variable.  55&nbsp;hypotenuse ()    # Calculate hypotenuse of a right triangle.  56&nbsp;{                # From "alt-bc.sh" example.  57&nbsp;distance=$(bc -l &#60;&#60; EOF  58&nbsp;scale = 0  59&nbsp;sqrt ( $1 * $1 + $2 * $2 )  60&nbsp;EOF  61&nbsp;)  62&nbsp;#  Setting "scale" to zero rounds down result to integer value,  63&nbsp;#+ a necessary compromise in this script.  64&nbsp;#  This diminshes the accuracy of the simulation, unfortunately.  65&nbsp;}  66&nbsp;  67&nbsp;  68&nbsp;# main() {  69&nbsp;  70&nbsp;# Initialize variables.  71&nbsp;shots=0  72&nbsp;splashes=0  73&nbsp;thuds=0  74&nbsp;Pi=0  75&nbsp;  76&nbsp;while [ "$shots" -lt  "$MAXSHOTS" ]           # Main loop.  77&nbsp;do  78&nbsp;  79&nbsp;  xCoord=$(get_random)                        # Get random X and Y coords.  80&nbsp;  yCoord=$(get_random)  81&nbsp;  hypotenuse $xCoord $yCoord                  #  Hypotenuse of right-triangle =  82&nbsp;                                              #+ distance.  83&nbsp;  ((shots++))  84&nbsp;  85&nbsp;  printf "#%4d   " $shots  86&nbsp;  printf "Xc = %4d  " $xCoord  87&nbsp;  printf "Yc = %4d  " $yCoord  88&nbsp;  printf "Distance = %5d  " $distance         #  Distance from   89&nbsp;                                              #+ center of lake --  90&nbsp;                                              #  the "origin" --  91&nbsp;                                              #+ coordinate (0,0).  92&nbsp;  93&nbsp;  if [ "$distance" -le "$DIMENSION" ]  94&nbsp;  then  95&nbsp;    echo -n "SPLASH!  "  96&nbsp;    ((splashes++))  97&nbsp;  else  98&nbsp;    echo -n "THUD!    "  99&nbsp;    ((thuds++)) 100&nbsp;  fi 101&nbsp; 102&nbsp;  Pi=$(echo "scale=9; $PMULTIPLIER*$splashes/$shots" | bc) 103&nbsp;  # Multiply ratio by 4.0. 104&nbsp;  echo -n "PI ~ $Pi" 105&nbsp;  echo 106&nbsp; 107&nbsp;done 108&nbsp; 109&nbsp;echo 110&nbsp;echo "After $shots shots, PI looks like approximately $Pi." 111&nbsp;# Tends to run a bit high . . .  112&nbsp;# Probably due to round-off error and imperfect randomness of $RANDOM. 113&nbsp;echo 114&nbsp; 115&nbsp;# } 116&nbsp; 117&nbsp;exit 0 118&nbsp; 119&nbsp;#  One might well wonder whether a shell script is appropriate for 120&nbsp;#+ an application as complex and computation-intensive as a simulation. 121&nbsp;# 122&nbsp;#  There are at least two justifications. 123&nbsp;#  1) As a proof of concept: to show it can be done. 124&nbsp;#  2) To prototype and test the algorithms before rewriting 125&nbsp;#+    it in a compiled high-level language.</PRE></TD></TR></TABLE><HR></DIV></DD><DT><ANAME="DCREF"></A><BCLASS="COMMAND">dc</B></DT><DD><P>The <BCLASS="COMMAND">dc</B> (<BCLASS="COMMAND">d</B>esk	    <BCLASS="COMMAND">c</B>alculator) utility is stack-oriented	      and uses RPN (<SPANCLASS="QUOTE">"Reverse Polish Notation"</SPAN>). Like	      <BCLASS="COMMAND">bc</B>, it has much of the power of a	      programming language.</P><P>Most persons avoid <BCLASS="COMMAND">dc</B>, since it	        requires non-intuitive RPN input. Yet, it has its uses.</P><DIVCLASS="EXAMPLE"><HR><ANAME="HEXCONVERT"></A><P><B>Example 15-49. Converting a decimal number to hexadecimal</B></P><TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="90%"><TR><TD><PRECLASS="PROGRAMLISTING">   1&nbsp;#!/bin/bash   2&nbsp;# hexconvert.sh: Convert a decimal number to hexadecimal.   3&nbsp;   4&nbsp;E_NOARGS=65 # Command-line arg missing.   5&nbsp;BASE=16     # Hexadecimal.   6&nbsp;   7&nbsp;if [ -z "$1" ]   8&nbsp;then   9&nbsp;  echo "Usage: $0 number"  10&nbsp;  exit $E_NOARGS  11&nbsp;  # Need a command line argument.  12&nbsp;fi  13&nbsp;# Exercise: add argument validity checking.  14&nbsp;  15&nbsp;  16&nbsp;hexcvt ()  17&nbsp;{  18&nbsp;if [ -z "$1" ]  19&nbsp;then  20&nbsp;  echo 0  21&nbsp;  return    # "Return" 0 if no arg passed to function.  22&nbsp;fi  23&nbsp;  24&nbsp;echo ""$1" "$BASE" o p" | dc  25&nbsp;#                 "o" sets radix (numerical base) of output.  26&nbsp;#                   "p" prints the top of stack.  27&nbsp;# See 'man dc' for other options.  28&nbsp;return  29&nbsp;}  30&nbsp;  31&nbsp;hexcvt "$1"  32&nbsp;  33&nbsp;exit 0</PRE></TD></TR></TABLE><HR></DIV><P>Studying the <ICLASS="FIRSTTERM">info</I> page for		<BCLASS="COMMAND">dc</B> is a painful path to understanding its		intricacies. There seems to be a small, select group of		<SPANCLASS="emphasis"><ICLASS="EMPHASIS">dc wizards</I></SPAN> who delight in showing off		their mastery of this powerful, but arcane utility.</P><P>	      <TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="90%"><TR><TD><PRECLASS="SCREEN"> <TTCLASS="PROMPT">bash$ </TT><TTCLASS="USERINPUT"><B>echo "16i[q]sa[ln0=aln100%Pln100/snlbx]sbA0D68736142snlbxq" | dc"</B></TT> <TTCLASS="COMPUTEROUTPUT">Bash</TT> 	      </PRE></TD></TR></TABLE>	  </P><DIVCLASS="EXAMPLE"><HR><ANAME="FACTR"></A><P><B>Example 15-50. Factoring</B></P><TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="90%"><TR><TD><PRECLASS="PROGRAMLISTING">   1&nbsp;#!/bin/bash   2&nbsp;# factr.sh: Factor a number   3&nbsp;   4&nbsp;MIN=2       # Will not work for number smaller than this.   5&nbsp;E_NOARGS=65   6&nbsp;E_TOOSMALL=66   7&nbsp;   8&nbsp;if [ -z $1 ]   9&nbsp;then  10&nbsp;  echo "Usage: $0 number"  11&nbsp;  exit $E_NOARGS  12&nbsp;fi  13&nbsp;  14&nbsp;if [ "$1" -lt "$MIN" ]  15&nbsp;then  16&nbsp;  echo "Number to factor must be $MIN or greater."  17&nbsp;  exit $E_TOOSMALL  18&nbsp;fi    19&nbsp;  20&nbsp;# Exercise: Add type checking (to reject non-integer arg).  21&nbsp;  22&nbsp;echo "Factors of $1:"  23&nbsp;# -------------------------------------------------------------------------------  24&nbsp;echo "$1[p]s2[lip/dli%0=1dvsr]s12sid2%0=13sidvsr[dli%0=1lrli2+dsi!&#62;.]ds.xd1&#60;2"|dc  25&nbsp;# -------------------------------------------------------------------------------  26&nbsp;# Above line of code written by Michel Charpentier &#60;charpov@cs.unh.edu&#62;.  27&nbsp;# Used in ABS Guide with permission (thanks!).  28&nbsp;  29&nbsp; exit 0</PRE></TD></TR></TABLE><HR></DIV></DD><DT><ANAME="AWKMATH"></A><BCLASS="COMMAND">awk</B></DT><DD><P>Yet another way of doing floating point math in	      a script is using <AHREF="awk.html#AWKREF">awk's</A>	      built-in math functions in a <AHREF="wrapper.html#SHWRAPPER">shell	      wrapper</A>.</P><DIVCLASS="EXAMPLE"><HR><ANAME="HYPOT"></A><P><B>Example 15-51. Calculating the hypotenuse of a triangle</B></P><TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="90%"><TR><TD><PRECLASS="PROGRAMLISTING">   1&nbsp;#!/bin/bash   2&nbsp;# hypotenuse.sh: Returns the "hypotenuse" of a right triangle.   3&nbsp;#                (square root of sum of squares of the "legs")   4&nbsp;   5&nbsp;ARGS=2                # Script needs sides of triangle passed.   6&nbsp;E_BADARGS=65          # Wrong number of arguments.   7&nbsp;   8&nbsp;if [ $# -ne "$ARGS" ] # Test number of arguments to script.   9&nbsp;then  10&nbsp;  echo "Usage: `basename $0` side_1 side_2"  11&nbsp;  exit $E_BADARGS  12&nbsp;fi  13&nbsp;  14&nbsp;  15&nbsp;AWKSCRIPT=' { printf( "%3.7f\n", sqrt($1*$1 + $2*$2) ) } '  16&nbsp;#             command(s) / parameters passed to awk  17&nbsp;  18&nbsp;  19&nbsp;# Now, pipe the parameters to awk.  20&nbsp;    echo -n "Hypotenuse of $1 and $2 = "  21&nbsp;    echo $1 $2 | awk "$AWKSCRIPT"  22&nbsp;#   ^^^^^^^^^^^^  23&nbsp;# An echo-and-pipe is an easy way of passing shell parameters to awk.  24&nbsp;  25&nbsp;exit 0  26&nbsp;  27&nbsp;# Exercise: Rewrite this script using 'bc' rather than awk.  28&nbsp;#           Which method is more intuitive?</PRE></TD></TR></TABLE><HR></DIV></DD></DL></DIV></DIV><DIVCLASS="NAVFOOTER"><HRALIGN="LEFT"WIDTH="100%"><TABLESUMMARY="Footer navigation table"WIDTH="100%"BORDER="0"CELLPADDING="0"CELLSPACING="0"><TR><TDWIDTH="33%"ALIGN="left"VALIGN="top"><AHREF="terminalccmds.html"ACCESSKEY="P">Prev</A></TD><TDWIDTH="34%"ALIGN="center"VALIGN="top"><AHREF="index.html"ACCESSKEY="H">Home</A></TD><TDWIDTH="33%"ALIGN="right"VALIGN="top"><AHREF="extmisc.html"ACCESSKEY="N">Next</A></TD></TR><TR><TDWIDTH="33%"ALIGN="left"VALIGN="top">Terminal Control Commands</TD><TDWIDTH="34%"ALIGN="center"VALIGN="top"><AHREF="external.html"ACCESSKEY="U">Up</A></TD><TDWIDTH="33%"ALIGN="right"VALIGN="top">Miscellaneous Commands</TD></TR></TABLE></DIV></BODY></HTML>

⌨️ 快捷键说明

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