Debian Codegraph @

HTML/mathc.html

raw symbols SCIP
1 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
2 <HTML
3 ><HEAD
4 ><TITLE
5 >Math Commands</TITLE
6 ><META
7 NAME="GENERATOR"
8 CONTENT="Modular DocBook HTML Stylesheet Version 1.76b+
9 "><LINK
10 REL="HOME"
11 TITLE="Advanced Bash-Scripting Guide"
12 HREF="index.html"><LINK
13 REL="UP"
14 TITLE="External Filters, Programs and Commands"
15 HREF="external.html"><LINK
16 REL="PREVIOUS"
17 TITLE="Terminal Control Commands"
18 HREF="terminalccmds.html"><LINK
19 REL="NEXT"
20 TITLE="Miscellaneous Commands"
21 HREF="extmisc.html"><META
22 HTTP-EQUIV="Content-Style-Type"
23 CONTENT="text/css"><LINK
24 REL="stylesheet"
25 HREF="common/kde-common.css"
26 TYPE="text/css"><META
27 HTTP-EQUIV="Content-Type"
28 CONTENT="text/html; charset=iso-8859-1"><META
29 HTTP-EQUIV="Content-Language"
30 CONTENT="en"><LINK
31 REL="stylesheet"
32 HREF="common/kde-localised.css"
33 TYPE="text/css"
34 TITLE="KDE-English"><LINK
35 REL="stylesheet"
36 HREF="common/kde-default.css"
37 TYPE="text/css"
38 TITLE="KDE-Default"></HEAD
39 ><BODY
40 CLASS="SECT1"
41 BGCOLOR="#FFFFFF"
42 TEXT="#000000"
43 LINK="#AA0000"
44 VLINK="#AA0055"
45 ALINK="#AA0000"
46 STYLE="font-family: sans-serif;"
47 ><DIV
48 CLASS="NAVHEADER"
49 ><TABLE
50 SUMMARY="Header navigation table"
51 WIDTH="100%"
52 BORDER="0"
53 CELLPADDING="0"
54 CELLSPACING="0"
55 ><TR
56 ><TH
57 COLSPAN="3"
58 ALIGN="center"
59 >Advanced Bash-Scripting Guide: An in-depth exploration of the art of shell scripting</TH
60 ></TR
61 ><TR
62 ><TD
63 WIDTH="10%"
64 ALIGN="left"
65 VALIGN="bottom"
66 ><A
67 HREF="terminalccmds.html"
68 ACCESSKEY="P"
69 >Prev</A
70 ></TD
71 ><TD
72 WIDTH="80%"
73 ALIGN="center"
74 VALIGN="bottom"
75 >Chapter 16. External Filters, Programs and Commands</TD
76 ><TD
77 WIDTH="10%"
78 ALIGN="right"
79 VALIGN="bottom"
80 ><A
81 HREF="extmisc.html"
82 ACCESSKEY="N"
83 >Next</A
84 ></TD
85 ></TR
86 ></TABLE
87 ><HR
88 ALIGN="LEFT"
89 WIDTH="100%"></DIV
90 ><DIV
91 CLASS="SECT1"
92 ><H1
93 CLASS="SECT1"
94 ><A
95 NAME="MATHC"
96 ></A
97 >16.8. Math Commands</H1
98 ><DIV
99 CLASS="VARIABLELIST"
100 ><P
101 ><B
102 ><A
103 NAME="MATHCOMMANDLISTING1"
104 ></A
105 ><SPAN
106 CLASS="QUOTE"
107 >"Doing the
108 numbers"</SPAN
109 ></B
110 ></P
111 ><DL
112 ><DT
113 ><A
114 NAME="FACTORREF"
115 ></A
116 ><B
117 CLASS="COMMAND"
118 >factor</B
119 ></DT
120 ><DD
121 ><P
122 >Decompose an integer into prime factors.</P
123 ><P
124 > <TABLE
125 BORDER="0"
126 BGCOLOR="#E0E0E0"
127 WIDTH="90%"
128 ><TR
129 ><TD
130 ><PRE
131 CLASS="SCREEN"
132 > <TT
133 CLASS="PROMPT"
134 >bash$ </TT
135 ><TT
136 CLASS="USERINPUT"
137 ><B
138 >factor 27417</B
139 ></TT
140 >
141 <TT
142 CLASS="COMPUTEROUTPUT"
143 >27417: 3 13 19 37</TT
144 >
145 </PRE
146 ></TD
147 ></TR
148 ></TABLE
149 >
150 </P
151 ><DIV
152 CLASS="EXAMPLE"
153 ><HR><A
154 NAME="PRIMES2"
155 ></A
156 ><P
157 ><B
158 >Example 16-46. Generating prime numbers</B
159 ></P
160 ><TABLE
161 BORDER="0"
162 BGCOLOR="#E0E0E0"
163 WIDTH="90%"
164 ><TR
165 ><TD
166 ><PRE
167 CLASS="PROGRAMLISTING"
168 > 1&nbsp;#!/bin/bash
169 2&nbsp;# primes2.sh
170 3&nbsp;
171 4&nbsp;# Generating prime numbers the quick-and-easy way,
172 5&nbsp;#+ without resorting to fancy algorithms.
173 6&nbsp;
174 7&nbsp;CEILING=10000 # 1 to 10000
175 8&nbsp;PRIME=0
176 9&nbsp;E_NOTPRIME=
177 10&nbsp;
178 11&nbsp;is_prime ()
179 12&nbsp;{
180 13&nbsp; local factors
181 14&nbsp; factors=( $(factor $1) ) # Load output of `factor` into array.
182 15&nbsp;
183 16&nbsp;if [ -z "${factors[2]}" ]
184 17&nbsp;# Third element of "factors" array:
185 18&nbsp;#+ ${factors[2]} is 2nd factor of argument.
186 19&nbsp;# If it is blank, then there is no 2nd factor,
187 20&nbsp;#+ and the argument is therefore prime.
188 21&nbsp;then
189 22&nbsp; return $PRIME # 0
190 23&nbsp;else
191 24&nbsp; return $E_NOTPRIME # null
192 25&nbsp;fi
193 26&nbsp;}
194 27&nbsp;
195 28&nbsp;echo
196 29&nbsp;for n in $(seq $CEILING)
197 30&nbsp;do
198 31&nbsp; if is_prime $n
199 32&nbsp; then
200 33&nbsp; printf %5d $n
201 34&nbsp; fi # ^ Five positions per number suffices.
202 35&nbsp;done # For a higher $CEILING, adjust upward, as necessary.
203 36&nbsp;
204 37&nbsp;echo
205 38&nbsp;
206 39&nbsp;exit</PRE
207 ></TD
208 ></TR
209 ></TABLE
210 ><HR></DIV
211 ></DD
212 ><DT
213 ><A
214 NAME="BCREF"
215 ></A
216 ><B
217 CLASS="COMMAND"
218 >bc</B
219 ></DT
220 ><DD
221 ><P
222 >Bash can't handle floating point calculations, and
223 it lacks operators for certain important mathematical
224 functions. Fortunately, <B
225 CLASS="COMMAND"
226 >bc</B
227 > gallops to
228 the rescue.</P
229 ><P
230 >Not just a versatile, arbitrary precision calculation
231 utility, <B
232 CLASS="COMMAND"
233 >bc</B
234 > offers many of the facilities of
235 a programming language. It has a syntax vaguely resembling
236 <B
237 CLASS="COMMAND"
238 >C</B
239 >.</P
240 ><P
241 >Since it is a fairly well-behaved UNIX utility, and may
242 therefore be used in a <A
243 HREF="special-chars.html#PIPEREF"
244 >pipe</A
245 >,
246 <B
247 CLASS="COMMAND"
248 >bc</B
249 > comes in handy in scripts.</P
250 ><P
251 ><A
252 NAME="BCTEMPLATE"
253 ></A
254 ></P
255 ><P
256 >Here is a simple template for using
257 <B
258 CLASS="COMMAND"
259 >bc</B
260 > to calculate a script
261 variable. This uses <A
262 HREF="commandsub.html#COMMANDSUBREF"
263 >command
264 substitution</A
265 >.</P
266 ><P
267 > <TABLE
268 BORDER="0"
269 BGCOLOR="#E0E0E0"
270 WIDTH="90%"
271 ><TR
272 ><TD
273 ><PRE
274 CLASS="SCREEN"
275 > <TT
276 CLASS="USERINPUT"
277 ><B
278 >variable=$(echo "OPTIONS; OPERATIONS" | bc)</B
279 ></TT
280 >
281 </PRE
282 ></TD
283 ></TR
284 ></TABLE
285 >
286 </P
287 ><P
288 ><A
289 NAME="MONTHLYPMT0"
290 ></A
291 ></P
292 ><DIV
293 CLASS="EXAMPLE"
294 ><HR><A
295 NAME="MONTHLYPMT"
296 ></A
297 ><P
298 ><B
299 >Example 16-47. Monthly Payment on a Mortgage</B
300 ></P
301 ><TABLE
302 BORDER="0"
303 BGCOLOR="#E0E0E0"
304 WIDTH="90%"
305 ><TR
306 ><TD
307 ><PRE
308 CLASS="PROGRAMLISTING"
309 > 1&nbsp;#!/bin/bash
310 2&nbsp;# monthlypmt.sh: Calculates monthly payment on a mortgage.
311 3&nbsp;
312 4&nbsp;
313 5&nbsp;# This is a modification of code in the
314 6&nbsp;#+ "mcalc" (mortgage calculator) package,
315 7&nbsp;#+ by Jeff Schmidt
316 8&nbsp;#+ and
317 9&nbsp;#+ Mendel Cooper (yours truly, the ABS Guide author).
318 10&nbsp;# http://www.ibiblio.org/pub/Linux/apps/financial/mcalc-1.6.tar.gz
319 11&nbsp;
320 12&nbsp;echo
321 13&nbsp;echo "Given the principal, interest rate, and term of a mortgage,"
322 14&nbsp;echo "calculate the monthly payment."
323 15&nbsp;
324 16&nbsp;bottom=1.0
325 17&nbsp;
326 18&nbsp;echo
327 19&nbsp;echo -n "Enter principal (no commas) "
328 20&nbsp;read principal
329 21&nbsp;echo -n "Enter interest rate (percent) " # If 12%, enter "12", not ".12".
330 22&nbsp;read interest_r
331 23&nbsp;echo -n "Enter term (months) "
332 24&nbsp;read term
333 25&nbsp;
334 26&nbsp;
335 27&nbsp; interest_r=$(echo "scale=9; $interest_r/100.0" | bc) # Convert to decimal.
336 28&nbsp; # ^^^^^^^^^^^^^^^^^ Divide by 100.
337 29&nbsp; # "scale" determines how many decimal places.
338 30&nbsp;
339 31&nbsp; interest_rate=$(echo "scale=9; $interest_r/12 + 1.0" | bc)
340 32&nbsp;
341 33&nbsp;
342 34&nbsp; top=$(echo "scale=9; $principal*$interest_rate^$term" | bc)
343 35&nbsp; # ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
344 36&nbsp; # Standard formula for figuring interest.
345 37&nbsp;
346 38&nbsp; echo; echo "Please be patient. This may take a while."
347 39&nbsp;
348 40&nbsp; let "months = $term - 1"
349 41&nbsp;# ====================================================================
350 42&nbsp; for ((x=$months; x &#62; 0; x--))
351 43&nbsp; do
352 44&nbsp; bot=$(echo "scale=9; $interest_rate^$x" | bc)
353 45&nbsp; bottom=$(echo "scale=9; $bottom+$bot" | bc)
354 46&nbsp;# bottom = $(($bottom + $bot"))
355 47&nbsp; done
356 48&nbsp;# ====================================================================
357 49&nbsp;
358 50&nbsp;# --------------------------------------------------------------------
359 51&nbsp;# Rick Boivie pointed out a more efficient implementation
360 52&nbsp;#+ of the above loop, which decreases computation time by 2/3.
361 53&nbsp;
362 54&nbsp;# for ((x=1; x &#60;= $months; x++))
363 55&nbsp;# do
364 56&nbsp;# bottom=$(echo "scale=9; $bottom * $interest_rate + 1" | bc)
365 57&nbsp;# done
366 58&nbsp;
367 59&nbsp;
368 60&nbsp;# And then he came up with an even more efficient alternative,
369 61&nbsp;#+ one that cuts down the run time by about 95%!
370 62&nbsp;
371 63&nbsp;# bottom=`{
372 64&nbsp;# echo "scale=9; bottom=$bottom; interest_rate=$interest_rate"
373 65&nbsp;# for ((x=1; x &#60;= $months; x++))
374 66&nbsp;# do
375 67&nbsp;# echo 'bottom = bottom * interest_rate + 1'
376 68&nbsp;# done
377 69&nbsp;# echo 'bottom'
378 70&nbsp;# } | bc` # Embeds a 'for loop' within command substitution.
379 71&nbsp;# --------------------------------------------------------------------------
380 72&nbsp;# On the other hand, Frank Wang suggests:
381 73&nbsp;# bottom=$(echo "scale=9; ($interest_rate^$term-1)/($interest_rate-1)" | bc)
382 74&nbsp;
383 75&nbsp;# Because . . .
384 76&nbsp;# The algorithm behind the loop
385 77&nbsp;#+ is actually a sum of geometric proportion series.
386 78&nbsp;# The sum formula is e0(1-q^n)/(1-q),
387 79&nbsp;#+ where e0 is the first element and q=e(n+1)/e(n)
388 80&nbsp;#+ and n is the number of elements.
389 81&nbsp;# --------------------------------------------------------------------------
390 82&nbsp;
391 83&nbsp;
392 84&nbsp; # let "payment = $top/$bottom"
393 85&nbsp; payment=$(echo "scale=2; $top/$bottom" | bc)
394 86&nbsp; # Use two decimal places for dollars and cents.
395 87&nbsp;
396 88&nbsp; echo
397 89&nbsp; echo "monthly payment = \$$payment" # Echo a dollar sign in front of amount.
398 90&nbsp; echo
399 91&nbsp;
400 92&nbsp;
401 93&nbsp; exit 0
402 94&nbsp;
403 95&nbsp;
404 96&nbsp; # Exercises:
405 97&nbsp; # 1) Filter input to permit commas in principal amount.
406 98&nbsp; # 2) Filter input to permit interest to be entered as percent or decimal.
407 99&nbsp; # 3) If you are really ambitious,
408 100&nbsp; #+ expand this script to print complete amortization tables.</PRE
409 ></TD
410 ></TR
411 ></TABLE
412 ><HR></DIV
413 ><P
414 ><A
415 NAME="BASE0"
416 ></A
417 ></P
418 ><DIV
419 CLASS="EXAMPLE"
420 ><HR><A
421 NAME="BASE"
422 ></A
423 ><P
424 ><B
425 >Example 16-48. Base Conversion</B
426 ></P
427 ><TABLE
428 BORDER="0"
429 BGCOLOR="#E0E0E0"
430 WIDTH="90%"
431 ><TR
432 ><TD
433 ><PRE
434 CLASS="PROGRAMLISTING"
435 > 1&nbsp;#!/bin/bash
436 2&nbsp;###########################################################################
437 3&nbsp;# Shellscript: base.sh - print number to different bases (Bourne Shell)
438 4&nbsp;# Author : Heiner Steven ([email protected])
439 5&nbsp;# Date : 07-03-95
440 6&nbsp;# Category : Desktop
441 7&nbsp;# $Id: base.sh,v 1.2 2000/02/06 19:55:35 heiner Exp $
442 8&nbsp;# ==&#62; Above line is RCS ID info.
443 9&nbsp;###########################################################################
444 10&nbsp;# Description
445 11&nbsp;#
446 12&nbsp;# Changes
447 13&nbsp;# 21-03-95 stv fixed error occuring with 0xb as input (0.2)
448 14&nbsp;###########################################################################
449 15&nbsp;
450 16&nbsp;# ==&#62; Used in ABS Guide with the script author's permission.
451 17&nbsp;# ==&#62; Comments added by ABS Guide author.
452 18&nbsp;
453 19&nbsp;NOARGS=85
454 20&nbsp;PN=`basename "$0"` # Program name
455 21&nbsp;VER=`echo '$Revision: 1.2 $' | cut -d' ' -f2` # ==&#62; VER=1.2
456 22&nbsp;
457 23&nbsp;Usage () {
458 24&nbsp; echo "$PN - print number to different bases, $VER (stv '95)
459 25&nbsp;usage: $PN [number ...]
460 26&nbsp;
461 27&nbsp;If no number is given, the numbers are read from standard input.
462 28&nbsp;A number may be
463 29&nbsp; binary (base 2) starting with 0b (i.e. 0b1100)
464 30&nbsp; octal (base 8) starting with 0 (i.e. 014)
465 31&nbsp; hexadecimal (base 16) starting with 0x (i.e. 0xc)
466 32&nbsp; decimal otherwise (i.e. 12)" &#62;&#38;2
467 33&nbsp; exit $NOARGS
468 34&nbsp;} # ==&#62; Prints usage message.
469 35&nbsp;
470 36&nbsp;Msg () {
471 37&nbsp; for i # ==&#62; in [list] missing. Why?
472 38&nbsp; do echo "$PN: $i" &#62;&#38;2
473 39&nbsp; done
474 40&nbsp;}
475 41&nbsp;
476 42&nbsp;Fatal () { Msg "$@"; exit 66; }
477 43&nbsp;
478 44&nbsp;PrintBases () {
479 45&nbsp; # Determine base of the number
480 46&nbsp; for i # ==&#62; in [list] missing...
481 47&nbsp; do # ==&#62; so operates on command-line arg(s).
482 48&nbsp; case "$i" in
483 49&nbsp; 0b*) ibase=2;; # binary
484 50&nbsp; 0x*|[a-f]*|[A-F]*) ibase=16;; # hexadecimal
485 51&nbsp; 0*) ibase=8;; # octal
486 52&nbsp; [1-9]*) ibase=10;; # decimal
487 53&nbsp; *)
488 54&nbsp; Msg "illegal number $i - ignored"
489 55&nbsp; continue;;
490 56&nbsp; esac
491 57&nbsp;
492 58&nbsp; # Remove prefix, convert hex digits to uppercase (bc needs this).
493 59&nbsp; number=`echo "$i" | sed -e 's:^0[bBxX]::' | tr '[a-f]' '[A-F]'`
494 60&nbsp; # ==&#62; Uses ":" as sed separator, rather than "/".
495 61&nbsp;
496 62&nbsp; # Convert number to decimal
497 63&nbsp; dec=`echo "ibase=$ibase; $number" | bc` # ==&#62; 'bc' is calculator utility.
498 64&nbsp; case "$dec" in
499 65&nbsp; [0-9]*) ;; # number ok
500 66&nbsp; *) continue;; # error: ignore
501 67&nbsp; esac
502 68&nbsp;
503 69&nbsp; # Print all conversions in one line.
504 70&nbsp; # ==&#62; 'here document' feeds command list to 'bc'.
505 71&nbsp; echo `bc &#60;&#60;!
506 72&nbsp; obase=16; "hex="; $dec
507 73&nbsp; obase=10; "dec="; $dec
508 74&nbsp; obase=8; "oct="; $dec
509 75&nbsp; obase=2; "bin="; $dec
510 76&nbsp;!
511 77&nbsp; ` | sed -e 's: : :g'
512 78&nbsp;
513 79&nbsp; done
514 80&nbsp;}
515 81&nbsp;
516 82&nbsp;while [ $# -gt 0 ]
517 83&nbsp;# ==&#62; Is a "while loop" really necessary here,
518 84&nbsp;# ==&#62;+ since all the cases either break out of the loop
519 85&nbsp;# ==&#62;+ or terminate the script.
520 86&nbsp;# ==&#62; (Above comment by Paulo Marcel Coelho Aragao.)
521 87&nbsp;do
522 88&nbsp; case "$1" in
523 89&nbsp; --) shift; break;;
524 90&nbsp; -h) Usage;; # ==&#62; Help message.
525 91&nbsp; -*) Usage;;
526 92&nbsp; *) break;; # First number
527 93&nbsp; esac # ==&#62; Error checking for illegal input might be appropriate.
528 94&nbsp; shift
529 95&nbsp;done
530 96&nbsp;
531 97&nbsp;if [ $# -gt 0 ]
532 98&nbsp;then
533 99&nbsp; PrintBases "$@"
534 100&nbsp;else # Read from stdin.
535 101&nbsp; while read line
536 102&nbsp; do
537 103&nbsp; PrintBases $line
538 104&nbsp; done
539 105&nbsp;fi
540 106&nbsp;
541 107&nbsp;
542 108&nbsp;exit</PRE
543 ></TD
544 ></TR
545 ></TABLE
546 ><HR></DIV
547 ><P
548 ><A
549 NAME="BCHEREDOC"
550 ></A
551 ></P
552 ><P
553 >An alternate method of invoking <B
554 CLASS="COMMAND"
555 >bc</B
556 >
557 involves using a <A
558 HREF="here-docs.html#HEREDOCREF"
559 >here
560 document</A
561 > embedded within a <A
562 HREF="commandsub.html#COMMANDSUBREF"
563 >command substitution</A
564 >
565 block. This is especially appropriate when a script
566 needs to pass a list of options and commands to
567 <B
568 CLASS="COMMAND"
569 >bc</B
570 >.</P
571 ><P
572 > <TABLE
573 BORDER="0"
574 BGCOLOR="#E0E0E0"
575 WIDTH="90%"
576 ><TR
577 ><TD
578 ><PRE
579 CLASS="PROGRAMLISTING"
580 > 1&nbsp;variable=`bc &#60;&#60; LIMIT_STRING
581 2&nbsp;options
582 3&nbsp;statements
583 4&nbsp;operations
584 5&nbsp;LIMIT_STRING
585 6&nbsp;`
586 7&nbsp;
587 8&nbsp;...or...
588 9&nbsp;
589 10&nbsp;
590 11&nbsp;variable=$(bc &#60;&#60; LIMIT_STRING
591 12&nbsp;options
592 13&nbsp;statements
593 14&nbsp;operations
594 15&nbsp;LIMIT_STRING
595 16&nbsp;)</PRE
596 ></TD
597 ></TR
598 ></TABLE
599 >
600 </P
601 ><DIV
602 CLASS="EXAMPLE"
603 ><HR><A
604 NAME="ALTBC"
605 ></A
606 ><P
607 ><B
608 >Example 16-49. Invoking <I
609 CLASS="FIRSTTERM"
610 >bc</I
611 > using a <I
612 CLASS="FIRSTTERM"
613 >here
614 document</I
615 ></B
616 ></P
617 ><TABLE
618 BORDER="0"
619 BGCOLOR="#E0E0E0"
620 WIDTH="90%"
621 ><TR
622 ><TD
623 ><PRE
624 CLASS="PROGRAMLISTING"
625 > 1&nbsp;#!/bin/bash
626 2&nbsp;# Invoking 'bc' using command substitution
627 3&nbsp;# in combination with a 'here document'.
628 4&nbsp;
629 5&nbsp;
630 6&nbsp;var1=`bc &#60;&#60; EOF
631 7&nbsp;18.33 * 19.78
632 8&nbsp;EOF
633 9&nbsp;`
634 10&nbsp;echo $var1 # 362.56
635 11&nbsp;
636 12&nbsp;
637 13&nbsp;# $( ... ) notation also works.
638 14&nbsp;v1=23.53
639 15&nbsp;v2=17.881
640 16&nbsp;v3=83.501
641 17&nbsp;v4=171.63
642 18&nbsp;
643 19&nbsp;var2=$(bc &#60;&#60; EOF
644 20&nbsp;scale = 4
645 21&nbsp;a = ( $v1 + $v2 )
646 22&nbsp;b = ( $v3 * $v4 )
647 23&nbsp;a * b + 15.35
648 24&nbsp;EOF
649 25&nbsp;)
650 26&nbsp;echo $var2 # 593487.8452
651 27&nbsp;
652 28&nbsp;
653 29&nbsp;var3=$(bc -l &#60;&#60; EOF
654 30&nbsp;scale = 9
655 31&nbsp;s ( 1.7 )
656 32&nbsp;EOF
657 33&nbsp;)
658 34&nbsp;# Returns the sine of 1.7 radians.
659 35&nbsp;# The "-l" option calls the 'bc' math library.
660 36&nbsp;echo $var3 # .991664810
661 37&nbsp;
662 38&nbsp;
663 39&nbsp;# Now, try it in a function...
664 40&nbsp;hypotenuse () # Calculate hypotenuse of a right triangle.
665 41&nbsp;{ # c = sqrt( a^2 + b^2 )
666 42&nbsp;hyp=$(bc -l &#60;&#60; EOF
667 43&nbsp;scale = 9
668 44&nbsp;sqrt ( $1 * $1 + $2 * $2 )
669 45&nbsp;EOF
670 46&nbsp;)
671 47&nbsp;# Can't directly return floating point values from a Bash function.
672 48&nbsp;# But, can echo-and-capture:
673 49&nbsp;echo "$hyp"
674 50&nbsp;}
675 51&nbsp;
676 52&nbsp;hyp=$(hypotenuse 3.68 7.31)
677 53&nbsp;echo "hypotenuse = $hyp" # 8.184039344
678 54&nbsp;
679 55&nbsp;
680 56&nbsp;exit 0</PRE
681 ></TD
682 ></TR
683 ></TABLE
684 ><HR></DIV
685 ><P
686 ><A
687 NAME="CANNONREF"
688 ></A
689 ></P
690 ><DIV
691 CLASS="EXAMPLE"
692 ><HR><A
693 NAME="CANNON"
694 ></A
695 ><P
696 ><B
697 >Example 16-50. Calculating PI</B
698 ></P
699 ><TABLE
700 BORDER="0"
701 BGCOLOR="#E0E0E0"
702 WIDTH="90%"
703 ><TR
704 ><TD
705 ><PRE
706 CLASS="PROGRAMLISTING"
707 > 1&nbsp;#!/bin/bash
708 2&nbsp;# cannon.sh: Approximating PI by firing cannonballs.
709 3&nbsp;
710 4&nbsp;# Author: Mendel Cooper
711 5&nbsp;# License: Public Domain
712 6&nbsp;# Version 2.2, reldate 13oct08.
713 7&nbsp;
714 8&nbsp;# This is a very simple instance of a "Monte Carlo" simulation:
715 9&nbsp;#+ a mathematical model of a real-life event,
716 10&nbsp;#+ using pseudorandom numbers to emulate random chance.
717 11&nbsp;
718 12&nbsp;# Consider a perfectly square plot of land, 10000 units on a side.
719 13&nbsp;# This land has a perfectly circular lake in its center,
720 14&nbsp;#+ with a diameter of 10000 units.
721 15&nbsp;# The plot is actually mostly water, except for land in the four corners.
722 16&nbsp;# (Think of it as a square with an inscribed circle.)
723 17&nbsp;#
724 18&nbsp;# We will fire iron cannonballs from an old-style cannon
725 19&nbsp;#+ at the square.
726 20&nbsp;# All the shots impact somewhere on the square,
727 21&nbsp;#+ either in the lake or on the dry corners.
728 22&nbsp;# Since the lake takes up most of the area,
729 23&nbsp;#+ most of the shots will SPLASH! into the water.
730 24&nbsp;# Just a few shots will THUD! into solid ground
731 25&nbsp;#+ in the four corners of the square.
732 26&nbsp;#
733 27&nbsp;# If we take enough random, unaimed shots at the square,
734 28&nbsp;#+ Then the ratio of SPLASHES to total shots will approximate
735 29&nbsp;#+ the value of PI/4.
736 30&nbsp;#
737 31&nbsp;# The simplified explanation is that the cannon is actually
738 32&nbsp;#+ shooting only at the upper right-hand quadrant of the square,
739 33&nbsp;#+ i.e., Quadrant I of the Cartesian coordinate plane.
740 34&nbsp;#
741 35&nbsp;#
742 36&nbsp;# Theoretically, the more shots taken, the better the fit.
743 37&nbsp;# However, a shell script, as opposed to a compiled language
744 38&nbsp;#+ with floating-point math built in, requires some compromises.
745 39&nbsp;# This decreases the accuracy of the simulation.
746 40&nbsp;
747 41&nbsp;
748 42&nbsp;DIMENSION=10000 # Length of each side of the plot.
749 43&nbsp; # Also sets ceiling for random integers generated.
750 44&nbsp;
751 45&nbsp;MAXSHOTS=1000 # Fire this many shots.
752 46&nbsp; # 10000 or more would be better, but would take too long.
753 47&nbsp;PMULTIPLIER=4.0 # Scaling factor.
754 48&nbsp;
755 49&nbsp;declare -r M_PI=3.141592654
756 50&nbsp; # Actual 9-place value of PI, for comparison purposes.
757 51&nbsp;
758 52&nbsp;get_random ()
759 53&nbsp;{
760 54&nbsp;SEED=$(head -n 1 /dev/urandom | od -N 1 | awk '{ print $2 }')
761 55&nbsp;RANDOM=$SEED # From "seeding-random.sh"
762 56&nbsp; #+ example script.
763 57&nbsp;let "rnum = $RANDOM % $DIMENSION" # Range less than 10000.
764 58&nbsp;echo $rnum
765 59&nbsp;}
766 60&nbsp;
767 61&nbsp;distance= # Declare global variable.
768 62&nbsp;hypotenuse () # Calculate hypotenuse of a right triangle.
769 63&nbsp;{ # From "alt-bc.sh" example.
770 64&nbsp;distance=$(bc -l &#60;&#60; EOF
771 65&nbsp;scale = 0
772 66&nbsp;sqrt ( $1 * $1 + $2 * $2 )
773 67&nbsp;EOF
774 68&nbsp;)
775 69&nbsp;# Setting "scale" to zero rounds down result to integer value,
776 70&nbsp;#+ a necessary compromise in this script.
777 71&nbsp;# It decreases the accuracy of this simulation.
778 72&nbsp;}
779 73&nbsp;
780 74&nbsp;
781 75&nbsp;# ==========================================================
782 76&nbsp;# main() {
783 77&nbsp;# "Main" code block, mimicking a C-language main() function.
784 78&nbsp;
785 79&nbsp;# Initialize variables.
786 80&nbsp;shots=0
787 81&nbsp;splashes=0
788 82&nbsp;thuds=0
789 83&nbsp;Pi=0
790 84&nbsp;error=0
791 85&nbsp;
792 86&nbsp;while [ "$shots" -lt "$MAXSHOTS" ] # Main loop.
793 87&nbsp;do
794 88&nbsp;
795 89&nbsp; xCoord=$(get_random) # Get random X and Y coords.
796 90&nbsp; yCoord=$(get_random)
797 91&nbsp; hypotenuse $xCoord $yCoord # Hypotenuse of
798 92&nbsp; #+ right-triangle = distance.
799 93&nbsp; ((shots++))
800 94&nbsp;
801 95&nbsp; printf "#%4d " $shots
802 96&nbsp; printf "Xc = %4d " $xCoord
803 97&nbsp; printf "Yc = %4d " $yCoord
804 98&nbsp; printf "Distance = %5d " $distance # Distance from
805 99&nbsp; #+ center of lake
806 100&nbsp; #+ -- the "origin" --
807 101&nbsp; #+ coordinate (0,0).
808 102&nbsp;
809 103&nbsp; if [ "$distance" -le "$DIMENSION" ]
810 104&nbsp; then
811 105&nbsp; echo -n "SPLASH! "
812 106&nbsp; ((splashes++))
813 107&nbsp; else
814 108&nbsp; echo -n "THUD! "
815 109&nbsp; ((thuds++))
816 110&nbsp; fi
817 111&nbsp;
818 112&nbsp; Pi=$(echo "scale=9; $PMULTIPLIER*$splashes/$shots" | bc)
819 113&nbsp; # Multiply ratio by 4.0.
820 114&nbsp; echo -n "PI ~ $Pi"
821 115&nbsp; echo
822 116&nbsp;
823 117&nbsp;done
824 118&nbsp;
825 119&nbsp;echo
826 120&nbsp;echo "After $shots shots, PI looks like approximately $Pi"
827 121&nbsp;# Tends to run a bit high,
828 122&nbsp;#+ possibly due to round-off error and imperfect randomness of $RANDOM.
829 123&nbsp;# But still usually within plus-or-minus 5% . . .
830 124&nbsp;#+ a pretty fair rough approximation.
831 125&nbsp;error=$(echo "scale=9; $Pi - $M_PI" | bc)
832 126&nbsp;pct_error=$(echo "scale=2; 100.0 * $error / $M_PI" | bc)
833 127&nbsp;echo -n "Deviation from mathematical value of PI = $error"
834 128&nbsp;echo " ($pct_error% error)"
835 129&nbsp;echo
836 130&nbsp;
837 131&nbsp;# End of "main" code block.
838 132&nbsp;# }
839 133&nbsp;# ==========================================================
840 134&nbsp;
841 135&nbsp;exit 0
842 136&nbsp;
843 137&nbsp;# One might well wonder whether a shell script is appropriate for
844 138&nbsp;#+ an application as complex and computation-intensive as a simulation.
845 139&nbsp;#
846 140&nbsp;# There are at least two justifications.
847 141&nbsp;# 1) As a proof of concept: to show it can be done.
848 142&nbsp;# 2) To prototype and test the algorithms before rewriting
849 143&nbsp;#+ it in a compiled high-level language.</PRE
850 ></TD
851 ></TR
852 ></TABLE
853 ><HR></DIV
854 ><P
855 >See also <A
856 HREF="contributed-scripts.html#STDDEV"
857 >Example A-37</A
858 >.</P
859 ></DD
860 ><DT
861 ><A
862 NAME="DCREF"
863 ></A
864 ><B
865 CLASS="COMMAND"
866 >dc</B
867 ></DT
868 ><DD
869 ><P
870 >The <B
871 CLASS="COMMAND"
872 >dc</B
873 > (<B
874 CLASS="COMMAND"
875 >d</B
876 >esk
877 <B
878 CLASS="COMMAND"
879 >c</B
880 >alculator) utility is <A
881 HREF="variables2.html#STACKDEFREF"
882 >stack-oriented</A
883 >
884 and uses RPN (<I
885 CLASS="FIRSTTERM"
886 >Reverse Polish Notation</I
887 >).
888 Like <B
889 CLASS="COMMAND"
890 >bc</B
891 >, it has much of the power of
892 a programming language.</P
893 ><P
894 >Similar to the procedure with <B
895 CLASS="COMMAND"
896 >bc</B
897 >,
898 <A
899 HREF="internal.html#ECHOREF"
900 >echo</A
901 > a command-string
902 to <B
903 CLASS="COMMAND"
904 >dc</B
905 >.</P
906 ><P
907 > <TABLE
908 BORDER="0"
909 BGCOLOR="#E0E0E0"
910 WIDTH="90%"
911 ><TR
912 ><TD
913 ><PRE
914 CLASS="PROGRAMLISTING"
915 > 1&nbsp;echo "[Printing a string ... ]P" | dc
916 2&nbsp;# The P command prints the string between the preceding brackets.
917 3&nbsp;
918 4&nbsp;# And now for some simple arithmetic.
919 5&nbsp;echo "7 8 * p" | dc # 56
920 6&nbsp;# Pushes 7, then 8 onto the stack,
921 7&nbsp;#+ multiplies ("*" operator), then prints the result ("p" operator).</PRE
922 ></TD
923 ></TR
924 ></TABLE
925 >
926 </P
927 ><P
928 >Most persons avoid <B
929 CLASS="COMMAND"
930 >dc</B
931 >, because
932 of its non-intuitive input and rather cryptic
933 operators. Yet, it has its uses.</P
934 ><DIV
935 CLASS="EXAMPLE"
936 ><HR><A
937 NAME="HEXCONVERT"
938 ></A
939 ><P
940 ><B
941 >Example 16-51. Converting a decimal number to hexadecimal</B
942 ></P
943 ><TABLE
944 BORDER="0"
945 BGCOLOR="#E0E0E0"
946 WIDTH="90%"
947 ><TR
948 ><TD
949 ><PRE
950 CLASS="PROGRAMLISTING"
951 > 1&nbsp;#!/bin/bash
952 2&nbsp;# hexconvert.sh: Convert a decimal number to hexadecimal.
953 3&nbsp;
954 4&nbsp;E_NOARGS=85 # Command-line arg missing.
955 5&nbsp;BASE=16 # Hexadecimal.
956 6&nbsp;
957 7&nbsp;if [ -z "$1" ]
958 8&nbsp;then # Need a command-line argument.
959 9&nbsp; echo "Usage: $0 number"
960 10&nbsp; exit $E_NOARGS
961 11&nbsp;fi # Exercise: add argument validity checking.
962 12&nbsp;
963 13&nbsp;
964 14&nbsp;hexcvt ()
965 15&nbsp;{
966 16&nbsp;if [ -z "$1" ]
967 17&nbsp;then
968 18&nbsp; echo 0
969 19&nbsp; return # "Return" 0 if no arg passed to function.
970 20&nbsp;fi
971 21&nbsp;
972 22&nbsp;echo ""$1" "$BASE" o p" | dc
973 23&nbsp;# o sets radix (numerical base) of output.
974 24&nbsp;# p prints the top of stack.
975 25&nbsp;# For other options: 'man dc' ...
976 26&nbsp;return
977 27&nbsp;}
978 28&nbsp;
979 29&nbsp;hexcvt "$1"
980 30&nbsp;
981 31&nbsp;exit</PRE
982 ></TD
983 ></TR
984 ></TABLE
985 ><HR></DIV
986 ><P
987 >Studying the <A
988 HREF="external.html#INFOREF"
989 >info</A
990 > page for
991 <B
992 CLASS="COMMAND"
993 >dc</B
994 > is a painful path to understanding its
995 intricacies. There seems to be a small, select group of
996 <SPAN
997 CLASS="emphasis"
998 ><I
999 CLASS="EMPHASIS"
1000 >dc wizards</I
1001 ></SPAN
1002 > who delight in showing off
1003 their mastery of this powerful, but arcane utility.</P
1004 ><P
1005 > <TABLE
1006 BORDER="0"
1007 BGCOLOR="#E0E0E0"
1008 WIDTH="90%"
1009 ><TR
1010 ><TD
1011 ><PRE
1012 CLASS="SCREEN"
1013 > <TT
1014 CLASS="PROMPT"
1015 >bash$ </TT
1016 ><TT
1017 CLASS="USERINPUT"
1018 ><B
1019 >echo "16i[q]sa[ln0=aln100%Pln100/snlbx]sbA0D68736142snlbxq" | dc</B
1020 ></TT
1021 >
1022 <TT
1023 CLASS="COMPUTEROUTPUT"
1024 >Bash</TT
1025 >
1026 </PRE
1027 ></TD
1028 ></TR
1029 ></TABLE
1030 >
1031 </P
1032 ><P
1033 ><A
1034 NAME="GOLDENRATIO"
1035 ></A
1036 >
1037 <TABLE
1038 BORDER="0"
1039 BGCOLOR="#E0E0E0"
1040 WIDTH="90%"
1041 ><TR
1042 ><TD
1043 ><PRE
1044 CLASS="PROGRAMLISTING"
1045 > 1&nbsp;dc &#60;&#60;&#60; 10k5v1+2/p # 1.6180339887
1046 2&nbsp;# ^^^ Feed operations to dc using a Here String.
1047 3&nbsp;# ^^^ Pushes 10 and sets that as the precision (10k).
1048 4&nbsp;# ^^ Pushes 5 and takes its square root
1049 5&nbsp;# (5v, v = square root).
1050 6&nbsp;# ^^ Pushes 1 and adds it to the running total (1+).
1051 7&nbsp;# ^^ Pushes 2 and divides the running total by that (2/).
1052 8&nbsp;# ^ Pops and prints the result (p)
1053 9&nbsp;# The result is 1.6180339887 ...
1054 10&nbsp;# ... which happens to be the Pythagorean Golden Ratio, to 10 places.</PRE
1055 ></TD
1056 ></TR
1057 ></TABLE
1058 >
1059 </P
1060 ><DIV
1061 CLASS="EXAMPLE"
1062 ><HR><A
1063 NAME="FACTR"
1064 ></A
1065 ><P
1066 ><B
1067 >Example 16-52. Factoring</B
1068 ></P
1069 ><TABLE
1070 BORDER="0"
1071 BGCOLOR="#E0E0E0"
1072 WIDTH="90%"
1073 ><TR
1074 ><TD
1075 ><PRE
1076 CLASS="PROGRAMLISTING"
1077 > 1&nbsp;#!/bin/bash
1078 2&nbsp;# factr.sh: Factor a number
1079 3&nbsp;
1080 4&nbsp;MIN=2 # Will not work for number smaller than this.
1081 5&nbsp;E_NOARGS=85
1082 6&nbsp;E_TOOSMALL=86
1083 7&nbsp;
1084 8&nbsp;if [ -z $1 ]
1085 9&nbsp;then
1086 10&nbsp; echo "Usage: $0 number"
1087 11&nbsp; exit $E_NOARGS
1088 12&nbsp;fi
1089 13&nbsp;
1090 14&nbsp;if [ "$1" -lt "$MIN" ]
1091 15&nbsp;then
1092 16&nbsp; echo "Number to factor must be $MIN or greater."
1093 17&nbsp; exit $E_TOOSMALL
1094 18&nbsp;fi
1095 19&nbsp;
1096 20&nbsp;# Exercise: Add type checking (to reject non-integer arg).
1097 21&nbsp;
1098 22&nbsp;echo "Factors of $1:"
1099 23&nbsp;# -------------------------------------------------------
1100 24&nbsp;echo "$1[p]s2[lip/dli%0=1dvsr]s12sid2%0=13sidvsr[dli%0=\
1101 25&nbsp;1lrli2+dsi!&#62;.]ds.xd1&#60;2" | dc
1102 26&nbsp;# -------------------------------------------------------
1103 27&nbsp;# Above code written by Michel Charpentier &#60;[email protected]&#62;
1104 28&nbsp;# (as a one-liner, here broken into two lines for display purposes).
1105 29&nbsp;# Used in ABS Guide with permission (thanks!).
1106 30&nbsp;
1107 31&nbsp; exit
1108 32&nbsp;
1109 33&nbsp; # $ sh factr.sh 270138
1110 34&nbsp; # 2
1111 35&nbsp; # 3
1112 36&nbsp; # 11
1113 37&nbsp; # 4093</PRE
1114 ></TD
1115 ></TR
1116 ></TABLE
1117 ><HR></DIV
1118 ></DD
1119 ><DT
1120 ><A
1121 NAME="AWKMATH"
1122 ></A
1123 ><B
1124 CLASS="COMMAND"
1125 >awk</B
1126 ></DT
1127 ><DD
1128 ><P
1129 >Yet another way of doing floating point math in
1130 a script is using <A
1131 HREF="awk.html#AWKREF"
1132 >awk's</A
1133 >
1134 built-in math functions in a <A
1135 HREF="wrapper.html#SHWRAPPER"
1136 >shell
1137 wrapper</A
1138 >.</P
1139 ><DIV
1140 CLASS="EXAMPLE"
1141 ><HR><A
1142 NAME="HYPOT"
1143 ></A
1144 ><P
1145 ><B
1146 >Example 16-53. Calculating the hypotenuse of a triangle</B
1147 ></P
1148 ><TABLE
1149 BORDER="0"
1150 BGCOLOR="#E0E0E0"
1151 WIDTH="90%"
1152 ><TR
1153 ><TD
1154 ><PRE
1155 CLASS="PROGRAMLISTING"
1156 > 1&nbsp;#!/bin/bash
1157 2&nbsp;# hypotenuse.sh: Returns the "hypotenuse" of a right triangle.
1158 3&nbsp;# (square root of sum of squares of the "legs")
1159 4&nbsp;
1160 5&nbsp;ARGS=2 # Script needs sides of triangle passed.
1161 6&nbsp;E_BADARGS=85 # Wrong number of arguments.
1162 7&nbsp;
1163 8&nbsp;if [ $# -ne "$ARGS" ] # Test number of arguments to script.
1164 9&nbsp;then
1165 10&nbsp; echo "Usage: `basename $0` side_1 side_2"
1166 11&nbsp; exit $E_BADARGS
1167 12&nbsp;fi
1168 13&nbsp;
1169 14&nbsp;
1170 15&nbsp;AWKSCRIPT=' { printf( "%3.7f\n", sqrt($1*$1 + $2*$2) ) } '
1171 16&nbsp;# command(s) / parameters passed to awk
1172 17&nbsp;
1173 18&nbsp;
1174 19&nbsp;# Now, pipe the parameters to awk.
1175 20&nbsp; echo -n "Hypotenuse of $1 and $2 = "
1176 21&nbsp; echo $1 $2 | awk "$AWKSCRIPT"
1177 22&nbsp;# ^^^^^^^^^^^^
1178 23&nbsp;# An echo-and-pipe is an easy way of passing shell parameters to awk.
1179 24&nbsp;
1180 25&nbsp;exit
1181 26&nbsp;
1182 27&nbsp;# Exercise: Rewrite this script using 'bc' rather than awk.
1183 28&nbsp;# Which method is more intuitive?</PRE
1184 ></TD
1185 ></TR
1186 ></TABLE
1187 ><HR></DIV
1188 ></DD
1189 ></DL
1190 ></DIV
1191 ></DIV
1192 ><DIV
1193 CLASS="NAVFOOTER"
1194 ><HR
1195 ALIGN="LEFT"
1196 WIDTH="100%"><TABLE
1197 SUMMARY="Footer navigation table"
1198 WIDTH="100%"
1199 BORDER="0"
1200 CELLPADDING="0"
1201 CELLSPACING="0"
1202 ><TR
1203 ><TD
1204 WIDTH="33%"
1205 ALIGN="left"
1206 VALIGN="top"
1207 ><A
1208 HREF="terminalccmds.html"
1209 ACCESSKEY="P"
1210 >Prev</A
1211 ></TD
1212 ><TD
1213 WIDTH="34%"
1214 ALIGN="center"
1215 VALIGN="top"
1216 ><A
1217 HREF="index.html"
1218 ACCESSKEY="H"
1219 >Home</A
1220 ></TD
1221 ><TD
1222 WIDTH="33%"
1223 ALIGN="right"
1224 VALIGN="top"
1225 ><A
1226 HREF="extmisc.html"
1227 ACCESSKEY="N"
1228 >Next</A
1229 ></TD
1230 ></TR
1231 ><TR
1232 ><TD
1233 WIDTH="33%"
1234 ALIGN="left"
1235 VALIGN="top"
1236 >Terminal Control Commands</TD
1237 ><TD
1238 WIDTH="34%"
1239 ALIGN="center"
1240 VALIGN="top"
1241 ><A
1242 HREF="external.html"
1243 ACCESSKEY="U"
1244 >Up</A
1245 ></TD
1246 ><TD
1247 WIDTH="33%"
1248 ALIGN="right"
1249 VALIGN="top"
1250 >Miscellaneous Commands</TD
1251 ></TR
1252 ></TABLE
1253 ></DIV
1254 ></BODY
1255 ></HTML
1256 >