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

📄 mathc.html

📁 Shall高级编程
💻 HTML
📖 第 1 页 / 共 2 页
字号:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><HTML><HEAD><TITLE>Math Commands</TITLE><METANAME="GENERATOR"CONTENT="Modular DocBook HTML Stylesheet Version 1.76b+"><LINKREL="HOME"TITLE="Advanced Bash-Scripting Guide"HREF="index.html"><LINKREL="UP"TITLE="External Filters, Programs and Commands"HREF="external.html"><LINKREL="PREVIOUS"TITLE="Terminal Control Commands"HREF="terminalccmds.html"><LINKREL="NEXT"TITLE="Miscellaneous Commands"HREF="extmisc.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="terminalccmds.html"ACCESSKEY="P">Prev</A></TD><TDWIDTH="80%"ALIGN="center"VALIGN="bottom">Chapter 15. External Filters, Programs and Commands</TD><TDWIDTH="10%"ALIGN="right"VALIGN="bottom"><AHREF="extmisc.html"ACCESSKEY="N">Next</A></TD></TR></TABLE><HRALIGN="LEFT"WIDTH="100%"></DIV><DIVCLASS="SECT1"><H1CLASS="SECT1"><ANAME="MATHC"></A>15.8. Math Commands</H1><DIVCLASS="VARIABLELIST"><P><B><ANAME="MATHCOMMANDLISTING1"></A><SPANCLASS="QUOTE">"Doing the	   numbers"</SPAN></B></P><DL><DT><ANAME="FACTORREF"></A><BCLASS="COMMAND">factor</B></DT><DD><P>Decompose an integer into prime factors.</P><P>	      <TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="90%"><TR><TD><PRECLASS="SCREEN"> <TTCLASS="PROMPT">bash$ </TT><TTCLASS="USERINPUT"><B>factor 27417</B></TT> <TTCLASS="COMPUTEROUTPUT">27417: 3 13 19 37</TT> 	      </PRE></TD></TR></TABLE>	    </P></DD><DT><ANAME="BCREF"></A><BCLASS="COMMAND">bc</B></DT><DD><P>Bash can't handle floating point calculations, and	      it lacks operators for certain important mathematical	      functions. Fortunately, <BCLASS="COMMAND">bc</B> comes to	      the rescue.</P><P>Not just a versatile, arbitrary precision calculation	      utility, <BCLASS="COMMAND">bc</B> offers many of the facilities of	      a programming language.</P><P><BCLASS="COMMAND">bc</B> has a syntax vaguely resembling C.</P><P>Since it is a fairly well-behaved UNIX utility, and may	       therefore be used in a <AHREF="special-chars.html#PIPEREF">pipe</A>,	       <BCLASS="COMMAND">bc</B> comes in handy in scripts.</P><P><ANAME="BCTEMPLATE"></A></P><P>Here is a simple template for using	      <BCLASS="COMMAND">bc</B> to calculate a script	      variable. This uses <AHREF="commandsub.html#COMMANDSUBREF">command	      substitution</A>.</P><P>              <TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="90%"><TR><TD><PRECLASS="SCREEN"> 	      <TTCLASS="USERINPUT"><B>variable=$(echo "OPTIONS; OPERATIONS" | bc)</B></TT> 	      </PRE></TD></TR></TABLE>	      </P><P><ANAME="MONTHLYPMT0"></A></P><DIVCLASS="EXAMPLE"><HR><ANAME="MONTHLYPMT"></A><P><B>Example 15-45. Monthly Payment on a Mortgage</B></P><TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="90%"><TR><TD><PRECLASS="PROGRAMLISTING">   1&nbsp;#!/bin/bash   2&nbsp;# monthlypmt.sh: Calculates monthly payment on a mortgage.   3&nbsp;   4&nbsp;   5&nbsp;#  This is a modification of code in the   6&nbsp;#+ "mcalc" (mortgage calculator) package,   7&nbsp;#+ by Jeff Schmidt   8&nbsp;#+ and   9&nbsp;#+ Mendel Cooper (yours truly, the author of the ABS Guide).  10&nbsp;#   http://www.ibiblio.org/pub/Linux/apps/financial/mcalc-1.6.tar.gz  [15k]  11&nbsp;  12&nbsp;echo  13&nbsp;echo "Given the principal, interest rate, and term of a mortgage,"  14&nbsp;echo "calculate the monthly payment."  15&nbsp;  16&nbsp;bottom=1.0  17&nbsp;  18&nbsp;echo  19&nbsp;echo -n "Enter principal (no commas) "  20&nbsp;read principal  21&nbsp;echo -n "Enter interest rate (percent) "  # If 12%, enter "12", not ".12".  22&nbsp;read interest_r  23&nbsp;echo -n "Enter term (months) "  24&nbsp;read term  25&nbsp;  26&nbsp;  27&nbsp; interest_r=$(echo "scale=9; $interest_r/100.0" | bc) # Convert to decimal.  28&nbsp;                 #           ^^^^^^^^^^^^^^^^^  Divide by 100.   29&nbsp;                 # "scale" determines how many decimal places.  30&nbsp;  31&nbsp; interest_rate=$(echo "scale=9; $interest_r/12 + 1.0" | bc)  32&nbsp;   33&nbsp;  34&nbsp; top=$(echo "scale=9; $principal*$interest_rate^$term" | bc)  35&nbsp;          #           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^  36&nbsp;          #           Standard formula for figuring interest.  37&nbsp;  38&nbsp; echo; echo "Please be patient. This may take a while."  39&nbsp;  40&nbsp; let "months = $term - 1"  41&nbsp;# ====================================================================   42&nbsp; for ((x=$months; x &#62; 0; x--))  43&nbsp; do  44&nbsp;   bot=$(echo "scale=9; $interest_rate^$x" | bc)  45&nbsp;   bottom=$(echo "scale=9; $bottom+$bot" | bc)  46&nbsp;#  bottom = $(($bottom + $bot"))  47&nbsp; done  48&nbsp;# ====================================================================   49&nbsp;  50&nbsp;# --------------------------------------------------------------------   51&nbsp;#  Rick Boivie pointed out a more efficient implementation  52&nbsp;#+ of the above loop, which decreases computation time by 2/3.  53&nbsp;  54&nbsp;# for ((x=1; x &#60;= $months; x++))  55&nbsp;# do  56&nbsp;#   bottom=$(echo "scale=9; $bottom * $interest_rate + 1" | bc)  57&nbsp;# done  58&nbsp;  59&nbsp;  60&nbsp;#  And then he came up with an even more efficient alternative,  61&nbsp;#+ one that cuts down the run time by about 95%!  62&nbsp;  63&nbsp;# bottom=`{  64&nbsp;#     echo "scale=9; bottom=$bottom; interest_rate=$interest_rate"  65&nbsp;#     for ((x=1; x &#60;= $months; x++))  66&nbsp;#     do  67&nbsp;#          echo 'bottom = bottom * interest_rate + 1'  68&nbsp;#     done  69&nbsp;#     echo 'bottom'  70&nbsp;#     } | bc`       # Embeds a 'for loop' within command substitution.  71&nbsp;# --------------------------------------------------------------------------  72&nbsp;#  On the other hand, Frank Wang suggests:  73&nbsp;#  bottom=$(echo "scale=9; ($interest_rate^$term-1)/($interest_rate-1)" | bc)  74&nbsp;  75&nbsp;#  Because . . .  76&nbsp;#  The algorithm behind the loop  77&nbsp;#+ is actually a sum of geometric proportion series.  78&nbsp;#  The sum formula is e0(1-q^n)/(1-q),  79&nbsp;#+ where e0 is the first element and q=e(n+1)/e(n)  80&nbsp;#+ and n is the number of elements.  81&nbsp;# --------------------------------------------------------------------------  82&nbsp;  83&nbsp;  84&nbsp; # let "payment = $top/$bottom"  85&nbsp; payment=$(echo "scale=2; $top/$bottom" | bc)  86&nbsp; # Use two decimal places for dollars and cents.  87&nbsp;   88&nbsp; echo  89&nbsp; echo "monthly payment = \$$payment"  # Echo a dollar sign in front of amount.  90&nbsp; echo  91&nbsp;  92&nbsp;  93&nbsp; exit 0  94&nbsp;  95&nbsp;  96&nbsp; # Exercises:  97&nbsp; #   1) Filter input to permit commas in principal amount.  98&nbsp; #   2) Filter input to permit interest to be entered as percent or decimal.  99&nbsp; #   3) If you are really ambitious, 100&nbsp; #+     expand this script to print complete amortization tables.</PRE></TD></TR></TABLE><HR></DIV><P><ANAME="BASE0"></A></P><DIVCLASS="EXAMPLE"><HR><ANAME="BASE"></A><P><B>Example 15-46. Base Conversion</B></P><TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="90%"><TR><TD><PRECLASS="PROGRAMLISTING">   1&nbsp;#!/bin/bash   2&nbsp;###########################################################################   3&nbsp;# Shellscript:	base.sh - print number to different bases (Bourne Shell)   4&nbsp;# Author     :	Heiner Steven (heiner.steven@odn.de)   5&nbsp;# Date       :	07-03-95   6&nbsp;# Category   :	Desktop   7&nbsp;# $Id: base.sh,v 1.2 2000/02/06 19:55:35 heiner Exp $   8&nbsp;# ==&#62; Above line is RCS ID info.   9&nbsp;###########################################################################  10&nbsp;# Description  11&nbsp;#  12&nbsp;# Changes  13&nbsp;# 21-03-95 stv	fixed error occuring with 0xb as input (0.2)  14&nbsp;###########################################################################  15&nbsp;  16&nbsp;# ==&#62; Used in ABS Guide with the script author's permission.  17&nbsp;# ==&#62; Comments added by ABS Guide author.  18&nbsp;  19&nbsp;NOARGS=65  20&nbsp;PN=`basename "$0"`			       # Program name  21&nbsp;VER=`echo '$Revision: 1.2 $' | cut -d' ' -f2`  # ==&#62; VER=1.2  22&nbsp;  23&nbsp;Usage () {  24&nbsp;    echo "$PN - print number to different bases, $VER (stv '95)  25&nbsp;usage: $PN [number ...]  26&nbsp;  27&nbsp;If no number is given, the numbers are read from standard input.  28&nbsp;A number may be  29&nbsp;    binary (base 2)		starting with 0b (i.e. 0b1100)  30&nbsp;    octal (base 8)		starting with 0  (i.e. 014)  31&nbsp;    hexadecimal (base 16)	starting with 0x (i.e. 0xc)  32&nbsp;    decimal			otherwise (i.e. 12)" &#62;&#38;2  33&nbsp;    exit $NOARGS   34&nbsp;}   # ==&#62; Function to print usage message.  35&nbsp;  36&nbsp;Msg () {  37&nbsp;    for i   # ==&#62; in [list] missing.  38&nbsp;    do echo "$PN: $i" &#62;&#38;2  39&nbsp;    done  40&nbsp;}  41&nbsp;  42&nbsp;Fatal () { Msg "$@"; exit 66; }  43&nbsp;  44&nbsp;PrintBases () {  45&nbsp;    # Determine base of the number  46&nbsp;    for i      # ==&#62; in [list] missing...  47&nbsp;    do         # ==&#62; so operates on command line arg(s).  48&nbsp;	case "$i" in  49&nbsp;	    0b*)		ibase=2;;	# binary  50&nbsp;	    0x*|[a-f]*|[A-F]*)	ibase=16;;	# hexadecimal  51&nbsp;	    0*)			ibase=8;;	# octal  52&nbsp;	    [1-9]*)		ibase=10;;	# decimal  53&nbsp;	    *)  54&nbsp;		Msg "illegal number $i - ignored"  55&nbsp;		continue;;  56&nbsp;	esac  57&nbsp;  58&nbsp;	# Remove prefix, convert hex digits to uppercase (bc needs this)  59&nbsp;	number=`echo "$i" | sed -e 's:^0[bBxX]::' | tr '[a-f]' '[A-F]'`  60&nbsp;	# ==&#62; Uses ":" as sed separator, rather than "/".  61&nbsp;  62&nbsp;	# Convert number to decimal  63&nbsp;	dec=`echo "ibase=$ibase; $number" | bc`  # ==&#62; 'bc' is calculator utility.  64&nbsp;	case "$dec" in  65&nbsp;	    [0-9]*)	;;			 # number ok  66&nbsp;	    *)		continue;;		 # error: ignore  67&nbsp;	esac  68&nbsp;  69&nbsp;	# Print all conversions in one line.  70&nbsp;	# ==&#62; 'here document' feeds command list to 'bc'.  71&nbsp;	echo `bc &#60;&#60;!  72&nbsp;	    obase=16; "hex="; $dec  73&nbsp;	    obase=10; "dec="; $dec  74&nbsp;	    obase=8;  "oct="; $dec  75&nbsp;	    obase=2;  "bin="; $dec  76&nbsp;!  77&nbsp;    ` | sed -e 's: :	:g'  78&nbsp;  79&nbsp;    done  80&nbsp;}  81&nbsp;  82&nbsp;while [ $# -gt 0 ]  83&nbsp;# ==&#62;  Is a "while loop" really necessary here,  84&nbsp;# ==&#62;+ since all the cases either break out of the loop  85&nbsp;# ==&#62;+ or terminate the script.  86&nbsp;# ==&#62; (Above comment by Paulo Marcel Coelho Aragao.)  87&nbsp;do  88&nbsp;    case "$1" in  89&nbsp;	--)     shift; break;;  90&nbsp;	-h)     Usage;;                 # ==&#62; Help message.  91&nbsp;	-*)     Usage;;  92&nbsp;         *)     break;;                 # first number  93&nbsp;    esac   # ==&#62; More error checking for illegal input might be useful.  94&nbsp;    shift  95&nbsp;done  96&nbsp;  97&nbsp;if [ $# -gt 0 ]  98&nbsp;then  99&nbsp;    PrintBases "$@" 100&nbsp;else					# read from stdin 101&nbsp;    while read line 102&nbsp;    do 103&nbsp;	PrintBases $line 104&nbsp;    done 105&nbsp;fi 106&nbsp; 107&nbsp; 108&nbsp;exit 0</PRE></TD></TR></TABLE><HR></DIV><P><ANAME="BCHEREDOC"></A></P><P>An alternate method of invoking <BCLASS="COMMAND">bc</B>		involves using a <AHREF="here-docs.html#HEREDOCREF">here		document</A> embedded within a <AHREF="commandsub.html#COMMANDSUBREF">command substitution</A>		block. This is especially appropriate when a script		needs to pass a list of options and commands to		<BCLASS="COMMAND">bc</B>.</P><P>	      <TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="90%"><TR><TD><PRECLASS="PROGRAMLISTING">   1&nbsp;variable=`bc &#60;&#60; LIMIT_STRING   2&nbsp;options   3&nbsp;statements   4&nbsp;operations   5&nbsp;LIMIT_STRING   6&nbsp;`   7&nbsp;   8&nbsp;...or...   9&nbsp;  10&nbsp;  11&nbsp;variable=$(bc &#60;&#60; LIMIT_STRING  12&nbsp;options  13&nbsp;statements  14&nbsp;operations  15&nbsp;LIMIT_STRING  16&nbsp;)</PRE></TD></TR></TABLE>              </P><DIVCLASS="EXAMPLE"><HR><ANAME="ALTBC"></A><P><B>Example 15-47. Invoking <ICLASS="FIRSTTERM">bc</I

⌨️ 快捷键说明

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