Performing Mathematical Calculations


The UNIX system provides several tools for doing mathematical operations. One of these is the factor command, which finds the prime factors of a positive integer. Some systems include the primes command, which can be used to generate a list of prime numbers. This section describes two of the most powerful and useful UNIX tools for mathematical calculations.

  • bc (basic calculator) is a powerful and flexible program for executing arithmetic calculations. It includes control statements and the ability to create and save userdefined functions.

  • dc (desk calculator) is an older alternative to bc. It uses the RPN (Reverse Polish Notation) method of entering data and operations (unlike bc, which uses the more familiar infix method).

bc

The bc command is both a calculator and a mini-language for writing mathematical programs. It provides all of the standard arithmetic operations, as well as a set of control statements and user-definable functions.

Using bc is fairly intuitive, as this example shows.

 $ bc 32+17 49 sqrt (49) 7 quit

As you can see, most arithmetic operators act just as you would expect. To add 32 and 17, just type 32+17, and bc will print the result. The command to find a square root is sqrt, and the command to exit bc is quit. To do longer strings of calculations, parentheses can be used to group terms:

 $ bc (( (1+5)*(3+4))/6)^2 49 quit

By default, bc does not save any decimal places in the result of a calculation. For example, if you try to find the square root of 2, it will report that the result is 1:

 $ bc sqrt(2) 1

The bc command can be used to do calculations to any degree of precision, but you must remember to specify how many decimal places to preserve (the scale). You do this by setting the variable scale to the appropriate number. For instance,

 scale=4 sqrt (2) 1.4142

This time the result shows the square root to four decimal places.

A number of common mathematical functions are available with the l (library) option. This tells bc to read in a set of predefined functions, including s (sine), c (cosine), a (arctangent), 1 (natural logarithm), and e (raises the constant e to a power). The following example shows how you could use the arctangent of 1 to find the approximate value of pi:

 $ bc −1 scale=6 a(1) * 4 3.141592

You can save the result of a calculation with a variable. For example, you might want to save the value of pi in order to use it in another line:

 pi=a(1) * 4 16*pi 50.265472

In newer versions of bc, the result of your latest calculation is automatically saved in the variable last.

Table 19–5 lists the most common bc operators, instructions, and functions.

Table 19–5: bc Operators and Functions

Symbol

Operation

Symbol

Operation

+

Addition

sqrt(x)

Square root

Subtraction

scale=n

Set scale

/

Division

ibase=n

Set input base

*

Multiplication

obase=n

Set output base

%

Remainder

define f(x)

Define function

A

Exponentiation

for, if, while

Control statements

()

Grouping

quit

Exit bc

Changing Bases

The bc command can be used to convert numbers from one base to another. The ibase variable sets the input base, and obase controls the output base. In the following example, when you enter the binary number 11010, bc displays the decimal equivalent, 26:

 $ bc ibase=2 11010 26 ibase=1010

To change back to the default input base of 10, you will need to enter the number 10 in the new base. So, in the preceding example, the line ibase=1010 returns to decimal input, since 1010 is binary for the number 10.

To convert typed decimal numbers to their hexadecimal representation, use obase:

 $ bc obase=16 41968 A3F0

This time you can return to decimal by typing obase=10, since you did not change the input base.

Control Statements

You can use bc control statements to write numerical programs or functions. The bc control statements include for, if, and while. Their syntax and use is the same as the corresponding statements in the C language. Curly brackets can be used to group terms that are part of a control statement.

The following example uses the for statement to compute the first four squares:

 $ bc for(i=1;i<=4;i=i+1) i^2 1 4 9 16

The next example uses while to print the squares of the first ten integers:

 x=1 while(x<=10) { x^2 x=x+1 

The following line tests the value of the variable x and, if it is greater than 10, sets y to 10:

 if(x>10) y=10

Defining Your Own Functions

You can define your own bc functions and use them just like built-in functions. The format of bc function definitions is the same as that of functions in the C language. The following illustrates how you could define and use a function:

 define pyth(a,b){ c=a^2+b^2 return(sqrt(c)) } pyth (3, 4) 5

Another example, which uses the for statement, is a function to compute factorials:

 define f(n) { auto x, i x=1 for (i=1;i<=n;i=i+1) x=x*i return(x) }

The bc command is ultimately rather limited for programming, but bc can be used in shell scripts to perform calculations. The next chapter describes shell scripting in detail, including a few examples with bc. Alternately, the awk language can be used to perform the same functions that bc provides, but it is more powerful and flexible. awk is described in Chapter 21.

Reading Functions from Files

The bc command allows you to read in a file and then continue to accept keyboard input. This allows you to build up libraries of bc programs and functions. For example, suppose you have saved the factorial function in a file called lib.bc. If you tell bc to read this file when it starts up, you can use these functions just like built-in functions. For instance,

 $ bc lib.bc f (5) 120

dc

The dc command gives you a calculator that uses the Reverse Polish Notation (RPN) method of entering data and operations. This approach is based on the concept of a stack that contains the data you enter, and operators that act on the numbers at the top of the stack.

When you enter a number, it is placed on top of the stack. Each new number is placed above the preceding one. An operation (+, , etc.) acts on the number or numbers on the top of the stack. In most cases, an operation replaces the numbers on top of the stack with the result of the operation.

Data and operators can be separated by any white space (a new line, space, or tab). You do not need a space between operator symbols. The following shows how you could use dc to add two numbers:

 $ dc 32 64+p 96 q $

In this example, the numbers 32 and 64 are added together. The “p” tells dc to print the result. The “q” is the instruction to quit the program.

The dc command provides the standard arithmetic operators, including remainder (%) and square root (v). The f command prints the full stack. A good way to learn about how dc works is to experiment with it, printing out the stack before and after each operation.

By default, dc does not save any decimal places in the result of a calculation. As with bc, you must remember to specify the scale. To set the scale, enter the desired number followed by k. For instance,

 4 k 2vp 1.4142

This example prints the square root of 2 to 4 decimal places.

There are no parentheses in dc. Because the result of each calculation is added to the top of the stack, it is possible to do long strings of calculations without them. The calculation

 $ bc (((1+5)*(3+4))/6)^2 49

would look like

 $ dc 1 5+ 3 4+ * 6/ 2^ 49

in dc. Notice that the second example is much more concise. This is one of the features of RPN that makes it very appealing to some people.

Table 19–6 shows the symbols for the basic dc operators.

Table 19–6: dc Operators

Symbol

Operation

Symbol

Operation

+

Addition

P

Print top item on stack

Subtraction

d

Duplicate top item on stack

/

Division

r

Reverse top two items on stack

*

Multiplication

f

Print entire stack

%

Remainder

c

Clear stack

^

Exponentiation

sx

Save to memory register x

v

Square root

lx

Load from register x

k

Set scale

l

Set input base

q or Q

Exit program

o

Set output base

Programming in dc

The dc language also includes instructions that you can use to write complex numerical programs. The syntax is very unintuitive, however, and most users will be much more comfortable using bc or another scripting language. Programmers who do learn to program in dc typically see it as an interesting challenge rather than a serious choice of language.

For those who are curious about the sort of programs that can be written in dc, Amit Singh has a remarkably readable example at http://www.kernelthread.com/hanvi/html/dc.html.




UNIX. The Complete Reference
UNIX: The Complete Reference, Second Edition (Complete Reference Series)
ISBN: 0072263369
EAN: 2147483647
Year: 2006
Pages: 316

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