12.8. Math Commands

"Doing the numbers"

factor

Decompose an integer into prime factors.

 bash$ factor 27417
 27417: 3 13 19 37
 	      

bc

Bash can't handle floating point calculations, and it lacks operators for certain important mathematical functions. Fortunately, bc comes to the rescue.

Not just a versatile, arbitrary precision calculation utility, bc offers many of the facilities of a programming language.

bc has a syntax vaguely resembling C.

Since it is a fairly well-behaved UNIX utility, and may therefore be used in a pipe, bc comes in handy in scripts.

Here is a simple template for using bc to calculate a script variable. This uses command substitution.

 	      variable=$(echo "OPTIONS; OPERATIONS" | bc)
 	      


Example 12-39. Monthly Payment on a Mortgage

   1 #!/bin/bash
   2 # monthlypmt.sh: Calculates monthly payment on a mortgage.
   3 
   4 
   5 #  This is a modification of code in the "mcalc" (mortgage calculator) package,
   6 #+ by Jeff Schmidt and Mendel Cooper (yours truly, the author of this document).
   7 #   http://www.ibiblio.org/pub/Linux/apps/financial/mcalc-1.6.tar.gz  [15k]
   8 
   9 echo
  10 echo "Given the principal, interest rate, and term of a mortgage,"
  11 echo "calculate the monthly payment."
  12 
  13 bottom=1.0
  14 
  15 echo
  16 echo -n "Enter principal (no commas) "
  17 read principal
  18 echo -n "Enter interest rate (percent) "  # If 12%, enter "12", not ".12".
  19 read interest_r
  20 echo -n "Enter term (months) "
  21 read term
  22 
  23 
  24  interest_r=$(echo "scale=9; $interest_r/100.0" | bc) # Convert to decimal.
  25                  # "scale" determines how many decimal places.
  26   
  27 
  28  interest_rate=$(echo "scale=9; $interest_r/12 + 1.0" | bc)
  29  
  30 
  31  top=$(echo "scale=9; $principal*$interest_rate^$term" | bc)
  32 
  33  echo; echo "Please be patient. This may take a while."
  34 
  35  let "months = $term - 1"
  36 # ==================================================================== 
  37  for ((x=$months; x > 0; x--))
  38  do
  39    bot=$(echo "scale=9; $interest_rate^$x" | bc)
  40    bottom=$(echo "scale=9; $bottom+$bot" | bc)
  41 #  bottom = $(($bottom + $bot"))
  42  done
  43 # -------------------------------------------------------------------- 
  44 #  Rick Boivie pointed out a more efficient implementation
  45 #+ of the above loop, which decreases computation time by 2/3.
  46 
  47 # for ((x=1; x <= $months; x++))
  48 # do
  49 #   bottom=$(echo "scale=9; $bottom * $interest_rate + 1" | bc)
  50 # done
  51 
  52 
  53 #  And then he came up with an even more efficient alternative,
  54 #+ one that cuts down the run time by about 95%!
  55 
  56 # bottom=`{
  57 #     echo "scale=9; bottom=$bottom; interest_rate=$interest_rate"
  58 #     for ((x=1; x <= $months; x++))
  59 #     do
  60 #          echo 'bottom = bottom * interest_rate + 1'
  61 #     done
  62 #     echo 'bottom'
  63 #     } | bc`       # Embeds a 'for loop' within command substitution.
  64 
  65 # ==================================================================== 
  66 
  67  # let "payment = $top/$bottom"
  68  payment=$(echo "scale=2; $top/$bottom" | bc)
  69  # Use two decimal places for dollars and cents.
  70  
  71  echo
  72  echo "monthly payment = \$$payment"  # Echo a dollar sign in front of amount.
  73  echo
  74 
  75 
  76  exit 0
  77 
  78  # Exercises:
  79  #   1) Filter input to permit commas in principal amount.
  80  #   2) Filter input to permit interest to be entered as percent or decimal.
  81  #   3) If you are really ambitious,
  82  #      expand this script to print complete amortization tables.


Example 12-40. Base Conversion

   1 #!/bin/bash
   2 ##########################################################################
   3 # Shellscript:	base.sh - print number to different bases (Bourne Shell)
   4 # Author     :	Heiner Steven (heiner.steven@odn.de)
   5 # Date       :	07-03-95
   6 # Category   :	Desktop
   7 # $Id: base.sh,v 1.2 2000/02/06 19:55:35 heiner Exp $
   8 # ==> Above line is RCS ID info.
   9 ##########################################################################
  10 # Description
  11 #
  12 # Changes
  13 # 21-03-95 stv	fixed error occuring with 0xb as input (0.2)
  14 ##########################################################################
  15 
  16 # ==> Used in this document with the script author's permission.
  17 # ==> Comments added by document author.
  18 
  19 NOARGS=65
  20 PN=`basename "$0"`			       # Program name
  21 VER=`echo '$Revision: 1.2 $' | cut -d' ' -f2`  # ==> VER=1.2
  22 
  23 Usage () {
  24     echo "$PN - print number to different bases, $VER (stv '95)
  25 usage: $PN [number ...]
  26 
  27 If no number is given, the numbers are read from standard input.
  28 A number may be
  29     binary (base 2)		starting with 0b (i.e. 0b1100)
  30     octal (base 8)		starting with 0  (i.e. 014)
  31     hexadecimal (base 16)	starting with 0x (i.e. 0xc)
  32     decimal			otherwise (i.e. 12)" >&2
  33     exit $NOARGS 
  34 }   # ==> Function to print usage message.
  35 
  36 Msg () {
  37     for i   # ==> in [list] missing.
  38     do echo "$PN: $i" >&2
  39     done
  40 }
  41 
  42 Fatal () { Msg "$@"; exit 66; }
  43 
  44 PrintBases () {
  45     # Determine base of the number
  46     for i      # ==> in [list] missing...
  47     do         # ==> so operates on command line arg(s).
  48 	case "$i" in
  49 	    0b*)		ibase=2;;	# binary
  50 	    0x*|[a-f]*|[A-F]*)	ibase=16;;	# hexadecimal
  51 	    0*)			ibase=8;;	# octal
  52 	    [1-9]*)		ibase=10;;	# decimal
  53 	    *)
  54 		Msg "illegal number $i - ignored"
  55 		continue;;
  56 	esac
  57 
  58 	# Remove prefix, convert hex digits to uppercase (bc needs this)
  59 	number=`echo "$i" | sed -e 's:^0[bBxX]::' | tr '[a-f]' '[A-F]'`
  60 	# ==> Uses ":" as sed separator, rather than "/".
  61 
  62 	# Convert number to decimal
  63 	dec=`echo "ibase=$ibase; $number" | bc`  # ==> 'bc' is calculator utility.
  64 	case "$dec" in
  65 	    [0-9]*)	;;			 # number ok
  66 	    *)		continue;;		 # error: ignore
  67 	esac
  68 
  69 	# Print all conversions in one line.
  70 	# ==> 'here document' feeds command list to 'bc'.
  71 	echo `bc <<!
  72 	    obase=16; "hex="; $dec
  73 	    obase=10; "dec="; $dec
  74 	    obase=8;  "oct="; $dec
  75 	    obase=2;  "bin="; $dec
  76 !
  77     ` | sed -e 's: :	:g'
  78 
  79     done
  80 }
  81 
  82 while [ $# -gt 0 ]
  83 # ==>  Is a "while loop" really necessary here,
  84 # ==>+ since all the cases either break out of the loop
  85 # ==>+ or terminate the script.
  86 # ==> (Thanks, Paulo Marcel Coelho Aragao.)
  87 do
  88     case "$1" in
  89 	--)     shift; break;;
  90 	-h)     Usage;;                 # ==> Help message.
  91 	-*)     Usage;;
  92          *)     break;;			# first number
  93     esac   # ==> More error checking for illegal input might be useful.
  94     shift
  95 done
  96 
  97 if [ $# -gt 0 ]
  98 then
  99     PrintBases "$@"
 100 else					# read from stdin
 101     while read line
 102     do
 103 	PrintBases $line
 104     done
 105 fi
 106 
 107 
 108 exit 0

An alternate method of invoking bc involves using a here document embedded within a command substitution block. This is especially appropriate when a script needs to pass a list of options and commands to bc.

   1 variable=`bc << LIMIT_STRING
   2 options
   3 statements
   4 operations
   5 LIMIT_STRING
   6 `
   7 
   8 ...or...
   9 
  10 
  11 variable=$(bc << LIMIT_STRING
  12 options
  13 statements
  14 operations
  15 LIMIT_STRING
  16 )


Example 12-41. Invoking bc using a "here document"

   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 hyp=             # Declare global variable.
  41 hypotenuse ()    # Calculate hypotenuse of a right triangle.
  42 {
  43 hyp=$(bc -l << EOF
  44 scale = 9
  45 sqrt ( $1 * $1 + $2 * $2 )
  46 EOF
  47 )
  48 # Unfortunately, can't return floating point values from a Bash function.
  49 }
  50 
  51 hypotenuse 3.68 7.31
  52 echo "hypotenuse = $hyp"    # 8.184039344
  53 
  54 
  55 exit 0


Example 12-42. Calculating PI

   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 all water, except for the four corners.
  12 #  (Think of it as a square with an inscribed circle.)
  13 #
  14 #  Let us fire iron cannonballs from an old-style cannon
  15 #+ at the square of land.
  16 #  All the shots impact somewhere on the plot of land,
  17 #+ either in the lake or on the dry corners.
  18 #  Since the lake takes up most of the land 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 land.
  22 #
  23 #  If we take enough random, unaimed shots at the plot of land,
  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, unfortunately.
  36 
  37 
  38 DIMENSION=10000  # Length of each side of the plot of land.
  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 -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.

dc

The dc (desk calculator) utility is stack-oriented and uses RPN ("Reverse Polish Notation"). Like bc, it has much of the power of a programming language.

Most persons avoid dc, since it requires non-intuitive RPN input. Yet it has its uses.


Example 12-43. Converting a decimal number to hexadecimal

   1 #!/bin/bash
   2 # hexconvert.sh: Convert a decimal number to hexadecimal.
   3 
   4 BASE=16     # Hexadecimal.
   5 
   6 if [ -z "$1" ]
   7 then
   8   echo "Usage: $0 number"
   9   exit $E_NOARGS
  10   # Need a command line argument.
  11 fi
  12 # Exercise: add argument validity checking.
  13 
  14 
  15 hexcvt ()
  16 {
  17 if [ -z "$1" ]
  18 then
  19   echo 0
  20   return    # "Return" 0 if no arg passed to function.
  21 fi
  22 
  23 echo ""$1" "$BASE" o p" | dc
  24 #                 "o" sets radix (numerical base) of output.
  25 #                   "p" prints the top of stack.
  26 # See 'man dc' for other options.
  27 return
  28 }
  29 
  30 hexcvt "$1"
  31 
  32 exit 0

Studying the info page for dc gives some insight into its intricacies. However, there seems to be a small, select group of dc wizards who delight in showing off their mastery of this powerful, but arcane utility.


Example 12-44. Factoring

   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 with permission (thanks).
  28 
  29  exit 0

awk

Yet another way of doing floating point math in a script is using awk's built-in math functions in a shell wrapper.


Example 12-45. Calculating the hypotenuse of a triangle

   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 echo -n "Hypotenuse of $1 and $2 = "
  20 echo $1 $2 | awk "$AWKSCRIPT"
  21 
  22 exit 0