Performing Math Tasks Using the Binary Calculator


Mathematics and calculation are common daily productivity fare in any office containing computer systems. Many offices use graphic spreadsheet programs, such as Microsoft Excel or Corel Quattro Pro.

As you might have predicted, the Linux command line gives you access to a more primitivebut also more programmableform of calculation. Using a programmable calculator like bc, you can automate long calculation procedures and have Linux prompt you for inputs, so that you don't miss steps or make mistakes. You can also call the binary calculator from shell applications of the kind you'll learn to develop in Chapter 25, "Harnessing the Power of the Shell."

Although it's a powerful performer, you need relatively little training to use the Linux binary calculator, called bc.

Starting bc and Performing Basic Calculations

To start the binary calculator, enter bc at the command line without arguments. When you do, you are dropped into the bc command mode:

 [you@workstation20 you]$ bc bc 1.06 Copyright 1991-1994, 1997, 1998, 2000 Free Software Foundation, Inc. This is free software with ABSOLUTELY NO WARRANTY. For details type 'warranty'. 

There is no bc prompt, but nevertheless bc patiently awaits your orders. To perform a basic calculation, just enter it naturally. For example, add a few numbers by entering digits and the plus operator as necessary, followed by pressing the Enter key:

 216 + 45 + 36 297 

Notice that bc instantly prints the result. You can use other mathematical operators by typing just the characters you would expect to type. Use parentheses to specify the order of operations, as in this example, which specifies 20 + 20 as the first calculation:

 ( 1200 / ( 20 + 20 ) ) * 6 180 

Again, the answer is instantly calculated and displayed.

You use a decimal point to indicate a fractional amount, as in this example:

 10.44 * 3.623 37.824 

You can exit bc at any time by entering the special command quit on an empty line:

 quit [you@workstation20 you]$ 

The capability to perform these types of small calculations quickly, easily, and with arbitrary precision (to any number of decimal places) makes the binary calculator extremely useful.

Using Variables

Sometimes remembering the results of calculations or storing numbers for later use is helpful. This can be done in bc as well. To make bc remember the results of calculations or numbers you want to use later, you can assign values or the results of calculated expressions to variables:

 a=10.1 b=6.3 c=a*b c 63.6 

Here, you assign the value 10.1 to the variable a, the value 6.3 to the variable b, and the result of multiplying a by b to variable c. You then display the contents of variable c by entering the name of the variable alone.

The results of division might at times be calculated to arbitrary levels of precision without reaching a conclusion. You can use the special variable scale to determine the number of decimal places that will be calculated when dividing:

 scale=10 3/7 .4285714285 

Using variables and the operators shown in these examples, you can perform a relatively long and complex series of calculations with ease and accuracy.

Automating Calculations in bc

Suppose you often perform a series of calculations over and over again. Rather than type the calculations repeatedly into bc using new numbers each time, you can write script to automate these types of calculations in bc. Here is an example:

  1. Using vi or emacs, create a file called addthree.bc, which contains the following text:

     "Number to add? "; y=read()"Adding 3 to "; y "produces "; y+3 quit 

  2. Call bc from the command line and supply addthree.bc as an argument.

  3. When bc prompts for a number, type a number and press Enter.

    The value of the number you enter is then stored by bc in the variable y and the number 3 is added to it. The result is then displayed:

     [you@workstation20 you]$ bc addthree.bc bc 1.06 Copyright 1991-1994, 1997, 1998, 2000 Free Software Foundation, Inc. This is free software with ABSOLUTELY NO WARRANTY. For details type `warranty'. Number to add? 7 Adding 3 to 7 produces 10 [you@workstation20 you]$ 

The read() command is used in a bc script to get a number from the user and store that number in a variable. You can prompt for any number of variables using the read() command, as shown previously. Text enclosed in quotation marks is output to the user as a prompt. Using these simple tools, you can automate relatively long and complex types of calculations.

Controlling Script Flow in bc

Scripting of any kind is infinitely more powerful if flow control (if/then statements or while statements) can be used. Flow control allows sections of your script (usually certain calculations) to be repeated over and over again until conditions that you specify are met. For example, if you are working on a calculus problem, you might repeat a calculation involving one variable over and over again until the value of that variable approaches zero, stopping afterward to output the number of times the calculation was performed.

Those familiar with the C computer programming language will find the flow control structures of the binary calculator familiar. Flow control allows you to enclose a list of calculations within a set of opening and closing braces ({}). Depending on the results of a comparison between two values, the calculations you've placed within the braces either are performed or are ignored.

Let's look at the two basic kinds of flow control and then examine them in more detail:

  • A calculation or set of calculations can be repeated using the while() {} flow control structure:

     while( y < 3 ) {     x = x + 1     y = x / 4 } 

    In this case, as long as the value of the variable y continues to be less than 3, the value of the variable x will be increased by 1, and the new value of x divided by 4 will be assigned to y.

  • An operation or set of operations can be executed conditionally using the if() {} structure:

     if( x == z ) {     "The two sums are equal. Input a new estimate? "; w=read()     y = x + w } 

    In this case, if the values of the variables x and z are equal, a new value for the variable w will be obtained from the user, added to the value for the variable x, and the results of the calculation will be stored in y.

Flow control operations can be nested inside one another to enhance functionality, as in the C language.

Notice that whether you're using while or if to determine whether the calculations inside the braces should be performed, the test itself goes in parentheses. The types of tests that can be performed inside the parentheses are shown in Table 22.1.

Table 22.1. Types of Flow Control Tests

Test

Explanation

value1 == value2

Calculations inside the braces will be performed if value1 and value2 are equal.

value1 < value2

Calculations inside the braces will be performed if value1 is less than value2.

value1 > value2

Calculations inside the braces will be performed if value1 is greater than value2.

value1 <= value2

Calculations inside the braces will be performed if value1 is less than or equal to value2.

value1 >= value2

Calculations inside the braces will be performed if value1 is greater than or equal to value2.


To illustrate the use of flow control, let's consider an example. Suppose you want to write a bc script that asks you for the number of rooms in a house, then asks you for the dimension of each room, and finally outputs the total number of square feet in the house as an answer. Listing 22.1 is just such a script. Start a text editor now, type it in, and save it as squarefeet.bc.

Listing 22.1. The squarefeet.bc Script
 1    "Enter the number of rooms in the house: " ; r = read() 2    c = 1 3    s = 0 4    while( c <= r ) { 5       "ROOM " ; c 6       "Enter length (in feet): " ; l = read() 7       "Enter width (in feet): " ; w = read() 8       s = s + ( l * w ) 9       c = c + 1 10   } 11   "Total square footage is " ; s 12   quit 

Indentation Makes Code More Readable

You may notice that some of the lines have been indented in Listing 22.1. It is common practice to indent blocks of calculations between braces ({}) to help in visualizing the structure of a bc script.


Before you exit your editor to return to the command line, let's study the way the script works:

  • Line 1 asks the user to enter the number of rooms in the house. This value is stored in the variable r.

  • Line 2 creates a variable, c, that will be used as a counter. Each time the script asks for the dimensions of another room, the value of c will be increased by 1. When the value of c matches the value of r (the number of rooms in the house), all rooms are accounted for, so the total is displayed and the script exits.

  • Line 3 creates a variable, s, that will hold the total square footage of the house so far, as the dimensions for each new room are entered.

  • Lines 410 are a while flow control element; the calculations inside the braces ({}) will be performed as long as the value in the variable c (the counter) is less than or equal to the variable r (the number of rooms).

  • Line 5 displays the current room number just before the script asks for room dimensions.

  • Lines 67 ask for the length and width of the room, respectively.

  • Line 8 multiples the length and width the user just entered to calculate the total number of square feet in the current room and then adds this value to s, the total number of square feet overall.

  • Line 9 adds 1 to the counter, c, to indicate that you have added one more room to the total.

  • Line 11 displays the total, after you have been asked for the measurements of each room.

  • Line 12 quits the binary calculator after the total is displayed.

Now that you have seen how the script works, exit your text editor and try calling bc at the command line using the script file named squarefeet.bc as an argument. Assume that you've measured a small house with five rooms, measuring 14x10, 12x10, 10x10, 11x8, and 6x5, respectively. The bc session follows:

 [you@workstation20 you]$ bc squarefeet.bc bc 1.06 Copyright 1991-1994, 1997, 1998, 2000 Free Software Foundation, Inc. This is free software with ABSOLUTELY NO WARRANTY. For details type `warranty'. Enter the number of rooms in the house: 5 ROOM 1 Enter length (in feet): 14 Enter width (in feet): 10 ROOM 2 Enter length (in feet): 12 Enter width (in feet): 10 ROOM 3 Enter length (in feet): 10 Enter width (in feet): 10 ROOM 4 Enter length (in feet): 11 Enter width (in feet): 8 ROOM 5 Enter length (in feet): 6 Enter width (in feet): 5 Total square footage is 478 [you@workstation20 you]$ 

You can see from the output of bc that the room-based square footage of this tiny house is 478 square feet. Many typical types of mathematical tasks can be automated in this way using the binary calculator. Many shell users and small businesses rely on a library of bc scripts that perform long, in-depth calculations that they routinely have to make. With bc scripts, these calculations are less error prone and completed more quickly.

There's a Lot More to bc

The binary calculator supports a large number of additional functions, operators, and comparisons that we haven't discussed here. It is possible to create relatively complex calculation procedures using bc. For an exhaustive discussion of the capabilities of bc, with examples, see the man page for bc.




    SAMS Teach Yourself Red Hat(r) Fedora(tm) 4 Linux(r) All in One
    Cisco ASA and PIX Firewall Handbook
    ISBN: N/A
    EAN: 2147483647
    Year: 2006
    Pages: 311
    Authors: David Hucaby

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net