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