bc(1) MPE/iX Shell and Utilities bc(1)
______________________________________________________________________
NAME
bc -- arbitrary-precision arithmetic calculation language
SYNOPSIS
bc [-i] [-l] [file...]
DESCRIPTION
bc is a programming language which can perform arithmetic calcu-
lations to arbitrary precision. You can use it interactively, by
entering instructions from the terminal. It can also run pro-
grams taken from files.
If you specify file arguments on the command line, they should be
text files containing bc instructions. bc performs the instruc-
tions from those files, in the order that they appear on the com-
mand line, and then performs instructions from the standard
input. bc terminates when it receives a quit instruction or
reaches the end-of-file on standard input.
Options
bc accepts the following options.
-i puts bc into interactive mode. In this mode, bc displays a
prompt when waiting for input. In addition, it handles
errors somewhat differently. Normally, when bc encounters
an error while processing a file, the interpreter displays
the error message and exits. In interactive mode, the
interpreter displays the message and returns to the prompt
mode to allow debugging.
-l loads a library of standard mathematical functions before
processing any other input. This library also sets the
scale to 20. For a description of the functions in the -l
library, see Built-in Functions.
The bc Language
bc is a simple but complete programming language with a syntax
reminiscent of the C programming language. This version of bc is
a superset of the standard language available on most systems. It
has a number of additional features intended to make the language
more flexible and useful. Features which are unique to this
implementation are noted in the text.
Input consists of a series of instructions that assign values to
variables or make calculations. It is also possible to define
subprograms called functions which perform a sequence of instruc-
tions to calculate a single value.
bc displays the result of any line that calculates a value, but
does not assign it to a variable. For example, the instruction
2+2
1
bc(1) MPE/iX Shell and Utilities bc(1)
______________________________________________________________________
displays
4
By default, bc displays the result of any evaluated instruction
followed by a newline. bc also saves the last value displayed in
a special variable . so that you can use it in subsequent calcu-
lations.
Numbers
Numbers consist of an optional minus (-) sign followed by a
sequence of zero or more digits, followed by an optional decimal
point (.), followed by a sequence of zero or more digits. Valid
digits are 0 through 9, and the hexadecimal digits A through F.
The uppercase letters represent the values from 10 through 15.
There must be at least one digit, either before or after the dec-
imal point. If not, bc interprets the decimal point as the spe-
cial variable . mentioned earlier.
A number can be arbitrarily long and may contain spaces. Here
are some valid numbers with an input base of 10:
0 0. .0 -3.14159 +09. -12 1 000 000
Here are some valid numbers with an input base of 16 (ibase=16):
0 FF FF.3 -10.444 A1
See Bases for more information.
A final point is that you cannot break up numbers with commas;
you can write 1000000 or 1 000 000, but 1,000,000 results in an
error message.
Identifiers
Identifiers are used as names for variables, functions, or
arrays. Valid identifiers may include sequences containing any
number of letters, digits or the underscore (_) character, but
must start with a lowercase letter. Spaces are not allowed in
identifiers. The ability to use identifiers more than one char-
acter in length is an extension not found in traditional imple-
mentations of bc.
* A variable holds a single numeric value. You can declare
variables as local to a function using the auto statement (see
Functions). All other variables are global and can be used any-
where. You do not need to declare global variables. bc cre-
ates variables as it requires them, with an initial value of
zero. (Remember that there is also the special variable .
(dot) which contains the result of the last calculation.)
* A function is a sequence of instructions that calculates a
single value. A list of zero or more values enclosed in
2
bc(1) MPE/iX Shell and Utilities bc(1)
______________________________________________________________________
parentheses always follow a function name, as in
my_func(3.14159). See Functions later in this man page.
* An array is a list of values. Values in the list are called
elements of the array. Each element in an array is numbered,
beginning at zero. Such a number is known as a subscript or
index of the array. Subscripts always appear in square
brackets after the array. For example, a[0] refers to element
zero in the array a. If a subscript value is a floating point
number, the fractional part is discarded to make the subscript
into an integer. For example, the following expressions all
refer to the same element:
a[3] a[3.2] a[3.999]
The maximum number of elements in a bc array is given by the
configuration variable {BC_DIM_MAX}. The valid array sub-
scripts range from 0 to -1 inclusive. Unlike many languages,
you don't need to declare the size of an array. Elements are
created dynamically as required, with an initial value of zero.
Since parentheses always follow function names and square
brackets always follow array names, bc can distinguish between
the three types of names. Therefore, you can have variables,
functions, and arrays with the same name. For example, foo may
be a variable, while foo() is a function and foo[] is an array.
Built-In Variables
bc has a number of built-in variables which are used to control
various aspects of the interpreter. These are described in the
following sections.
Scale
The scale value is the number of digits to be retained after the
decimal point in arithmetic operations. For example, if the
scale is three, each calculation retains at least three digits
after the decimal point. This means that
5 / 3
has the value
1.666
If -l is specified, the scale is set to 20; otherwise the default
scale is zero.
The variable scale holds the current scale value. To change
scales, assign a new value to scale, as in
scale = 5
Since scale is just a regular bc variable, it can be used in the
3
bc(1) MPE/iX Shell and Utilities bc(1)
______________________________________________________________________
full range of bc expressions.
The number of decimal places in the result of a calculation is
affected not only by the scale, but also by the number of decimal
places in the operands of the calculation. This is discussed in
detail in the Operations section.
There is also a function scale() which can determine the scale of
any expression. For example,
scale(1.1234)
returns the result four, which is the scale of the number 1.1234.
The result of the scale() function is always an integer (that is,
it has a scale of 0).
The maximum value for scale is given by the configuration vari-
able {BC_SCALE_MAX} and the minimum value is 0.
Bases
bc lets you specify numbers in different bases, for example,
octal (base 8) or hexadecimal (base 16). You can input numbers
in one base and output them in a different base, simplifying the
job of converting from one base to another. bc does this using
the built-in variables ibase and obase
ibase is the base for input numbers. It has an initial value of
10 (normal decimal numbers). To use a different base for input-
ting numbers, assign an integer to ibase, as in
ibase = 8
This says that all future input numbers will be in base 8
(octal). The largest valid input base is 16 and the smallest
valid input base is 2. Since there is no mechanism provided to
represent digits larger than 15, bases larger than 16 are essen-
tially useless. When the base is greater than 10, use the upper-
case letters as digits. For example, base 16 uses the digits 0
through 9, and A through F. The digits are allowed in any num-
ber, regardless of the setting of ibase but are largely meaning-
less if the base is smaller than the digit. The one case where
this is useful is in resetting the input base to 10. The con-
stant A always has the value 10 no matter what ibase is set to,
so to reset the input base to 10, type
ibase = A
obase is the base in which numbers are output. It has an initial
value of 10 (normal decimal numbers). To change output bases,
assign an appropriate integer to obase.
If the output base is 16 or less, bc displays numbers with normal
4
bc(1) MPE/iX Shell and Utilities bc(1)
______________________________________________________________________
digits and hexadecimal digits (if needed). The output base can
also be greater than 16, in which case each digit is displayed as
a decimal value and digits are separated by a single space. For
example, if obase is 1000, the decimal number 123456789 is
displayed as
123 456 789
Here, the digits are decimal values from 0 through 999. As a
result, all output values are broken up into one or more chunks
with three digits per chunk. Using output bases that are large
powers of 10, you can columnate your output; for example, many
users find that 100000 makes a good output base because numbers
are grouped into chunks of five digits each.
Long numbers are output with a maximum of 70 characters per line.
If a number is longer than this, bc puts a backslash (\) at the
end of the line, indicating that the number is continued on the
next line.
Internal calculations are performed in decimal, regardless of the
input and output bases. Therefore, the number of places after
the decimal point are dictated by the scale when numbers are
expressed in decimal form.
The maximum value for obase is given by the configuration vari-
able {BC_BASE_MAX}.
Arithmetic Operations
bc provides a large number of arithmetic operations. Following
standard arithmetic conventions, some operations are calculated
before others; for example, multiplication take place before
addition unless you use parentheses to group operations. Opera-
tions that take place first are said to have a higher precedence
than operations which take place later.
Operations also have an associativity. The associativity dictates
the order of evaluation when you have a sequence of operations
with equal precedence. Some operations are evaluated left to
right while others are evaluated right to left. The Operator
Associativity table shows the operators of bc from highest prece-
dence to lowest. Programmers familiar with C will note that bc's
order of precedence is not the same as C's. In C, assignment
operators have the lowest precedence. The precedence is shown in
Table 1, bc Operators.
5
bc(1) MPE/iX Shell and Utilities bc(1)
______________________________________________________________________
_______________________________________
| Operator Associativity |
|______________________________________|
|( ) left to right |
|unary ++ -- not applicable |
|unary - ! not applicable |
|^ right to left |
|* / % left to right |
|+ - left to right |
|= ^= *= /= %= += right to left |
|== <= >= != < > none |
|&& left to right |
||| left to right |
|______________________________________|
Table 1: bc Operators
The following list describes each operator. In the descriptions,
A and B can be numbers, variables, array elements, or other
expressions. V must be either a variable or an array element.
(A) An expression in parentheses is evaluated before any
other operations are performed on it.
-A is the negation of the expression.
!A is the logical complement of the expression. If A evalu-
ates to zero, !A evaluates to one. If A is not zero, !A
evaluates to zero. This operator is unique to this ver-
sion of bc.
++V adds 1 to the value of V. The result of the expression is
the new value of V.
--V subtracts 1 from the value of V. The result of the
expression is the new value of V.
V++ adds 1 to the value of V, but the result of the expres-
sion is the old value of V.
V-- subtracts 1 from the value of V, but the result of the
expression is the old value of V.
A ^ B calculates A to the power B. B must be an integer. The
scale of the result of A^B is
min(scale(A) * abs(B), max(scale, scale(A)))
where min() calculates the minimum of a set of numbers
and max() calculates the maximum.
6
bc(1) MPE/iX Shell and Utilities bc(1)
______________________________________________________________________
A * B calculates A multiplied by B. The scale of the result is
min(scale(A) + scale(B), max(scale, scale(A), scale(B)))
A / B calculates A divided by B. The scale of the result is the
value of scale.
A % B calculates the remainder from the division of A by B.
This is calculated in two steps. First, bc calculates
A/B to the current scale. It then obtains the remainder
through the formula
A - (A / B) * B
calculated to the scale
max(scale + scale(B), scale(A))
A + B adds A plus B. The scale of the result is the maximum of
the two scales of the operands.
A - B calculates A minus B. The scale of the result is the max-
imum of the two scales of the operands.
The next group of operators are all assignment operators. They
assign values to objects. An assignment operation has a value:
the value that is being assigned. Therefore you can write opera-
tions like a=1+(b=2). In this operation, the value of the assign-
ment in parentheses is 2 because that is the value assigned to b.
Therefore, the value 3 is assigned to a. The possible assignment
operators are:
V = B assigns the value of B to V.
V ^= B is equivalent to V=V^B.
V *= B is equivalent to V=V*B.
V /= B is equivalent to V=V/B.
V %= B is equivalent to V=V%B.
V += B is equivalent to V=V+B.
V -= B is equivalent to V=V-B.
The following expressions are called relations, and their values
can be either true (one) or false (zero). This version of bc
lets you use the relational operators in any expression, not just
in the conditional parts of if, while, or for statements. These
operators work in exactly the same way as their equivalents in
7
bc(1) MPE/iX Shell and Utilities bc(1)
______________________________________________________________________
the C language. The result of a relation is zero if the relation
is false and one if the relation is true.
A == B is true if and only if A equals B.
A <= B is true if and only if A is less than or equal to B.
A >= B is true if and only if A is greater than or equal to B.
A != B is true if and only if A is not equal to B.
A < B is true if and only if A is less than B.
A > B is true if and only if A is greater than B.
A && B is true if and only if A is true (non-zero) and B is
true. If A is not true, the expression B is never
evaluated.
A || B is true if A is true or B is true. If A is true, the
expression B is never evaluated.
Comments and White Space
A comment has the form
/* Any string */
Comments can extend over more than one line of text. When bc
sees /* at the start of a comment, it discards everything up to
the next */. The only effect a comment has is to indicate the end
of a token.
As an extension, this version of bc also provides an additional
comment convention using the # character. All text from the # to
the end of the current line is treated as a single blank, as in
2+2 # this is a comment
bc is free format. You may freely insert blanks or horizontal
tab characters to improve the readability of the code. Instruc-
tions are assumed to end at the end of the line. If you have an
instruction that is so long you need to continue it onto a new
line, put a backslash (\) as the last character of the first line
and continue the instruction on the next line. For example,
a = 2\
+ 3
This is equivalent to
a = 2 + 3
8
bc(1) MPE/iX Shell and Utilities bc(1)
______________________________________________________________________
Instructions
A bc instruction may be an expression that performs a calcula-
tion, an assignment, a function definition, or a statement. If
an instruction is not an assignment, bc displays the result of
the instruction when it has completed the calculation. For
example, if you enter
3.14 * 23
bc displays the result of the calculation. However, with
a = 3.14 * 23
bc does not display anything because the expression is an assign-
ment. If you do want to display the value of an assignment
expression, place the expression in parentheses.
The following list shows the instruction formats recognized by
bc.
expression
calculates the value of the expression.
"string"
is a string constant. When bc sees a statement with this for-
mat, it displays the contents of the string. For example,
"Hello world!"
tells bc to display Hello world! A newline character is not
output after the string. This makes it possible to do things
like
foo = 15
"The value of foo is "; foo
With these instructions, bc displays
The value of foo is 15
statement ; statement ...
is a sequence of statements on the same line. In bc, a semi-
colon (;) is equivalent to a newline. They both indicate the
end of a statement. bc performs these statements from left to
right.
{statement}
is a brace-bracketed statement. Brace brackets are used to
group sequences of statements together, as in
9
bc(1) MPE/iX Shell and Utilities bc(1)
______________________________________________________________________
{
statement
...
}
Brace brackets can group a series of statements which are
split over several lines. They are usually used with control
statements like if and while.
break
can only be used inside a while or for loop. break terminates
the loop.
for (initexp ; relation ; endexp) statement
is equivalent to
initexp
while (relation) {
statement
endexp
}
where initexp and endexp are expressions and relation is a
relation. For example,
a = 0
for (i = 1; i <= 10; ++i) a += i
is equivalent to the while example given earlier. C program-
mers should note that all three items inside the parentheses
must be specified; unlike C, bc does not let you omit any of
these expressions.
if (relation) statement
tests whether the given relation is true. If it is, bc per-
forms the statement; otherwise, bc skips over statement and
goes to the next instruction. For example,
if ((a%2) == 0) "a is even"
displays a is even if a has an even value.
if (relation) statement1 else statement2
is similar to the simple if statement. If relation is true,
it performs statement1; otherwise, it performs statement2. It
may be used as follows:
if ((a%2) == 0) "a is even" else "a is odd"
Note: There is no statement separator between "a is even" and
the else keyword. This differs from the C language.
10
bc(1) MPE/iX Shell and Utilities bc(1)
______________________________________________________________________
Here is another example:
if (a<10) {
"a "
"is "; "less than 10 "
a
} else {
"a is"
" greater than 10 "
a
}
Note: The braces must be on the same line as the if and the else
keywords. This is because a newline or a semicolon right after
(relation) indicates that the body of the statement is null. One
common source of errors in bc programs is typing the statement
portion of an if statement on a separate line. If -i is used,
the interpreter displays a warning when if statements with null
bodies are encountered.
while (relation) statement
repeatedly performs the given statement while relation is
true. For example,
i = 1
a = 0
while (i <= 10) {
a += i
++i
}
adds the integers from 1 through 10 and stores the result in
a.
If the relation is not true when bc encounters the while loop,
bc does not perform statement.
print expression , expression ...
displays the results of the expressions. Normally bc displays
the value of each expression or string it encounters. This
makes it difficult to format your output in programs. For
this reason, the MPE/iX Shell and Utilities version of bc has
a print statement to give you more control over how things are
displayed. print lets you display several numbers on the same
line with strings. This statement displays all of its argu-
ments on a single line. A single space is displayed between
adjacent numbers (but not between numbers and strings). A
print statement with no arguments displays a newline. If the
last argument is null, subsequent output continues on the same
line. Here are some examples of how to use print:
11
bc(1) MPE/iX Shell and Utilities bc(1)
______________________________________________________________________
/* basic print statement */
print "The square of ", 2, "is ", 2*2
The square of 2 is 4
/* inserts a space between adjacent numbers */
print 1,2,3
1 2 3
/* note - no spaces */
print 1,"",2,"",3
123
/* just print a blank line */
print
/* two statements with output on same line */
print 1,2,3, ; print 4, 5, 6
1 2 3 4 5 6
quit
terminates bc. In other implementations of bc, the inter-
preter exits as soon as it reads this token. This version of
bc treats quit as a real statement, so you can use it in
loops, functions, and so on.
sh ...
lets you send a line to the MPE/iX Shell for execution, as in
sh more <foo
This command passes everything from the first non-blank char-
acter until the end of the line to the shell for execution.
void expression
void throws away or voids the result of the evaluation of
expression instead of displaying it. This is useful when
using ++ and -- operators, or when you want to use a function
but don't want to use the return value for anything. For
example,
void foo++
increments foo but does not display the result. The void
statement is unique to this version of bc.
Several other types of statements are only relevant in function
definitions. These are described in the next section.
Functions
A function is a subprogram to calculate a result based on argu-
ment values. For example, the following function converts a tem-
perature given in Fahrenheit into the equivalent temperature in
12
bc(1) MPE/iX Shell and Utilities bc(1)
______________________________________________________________________
Celsius.
define f_to_c(f) {
return ((f-32) * 5 / 9)
}
This defines a function named f_to_c() that takes a single argu-
ment called f. The body of the function is enclosed in brace
brackets. The opening brace must be on the same line as the
define keyword. The function body consists of a sequence of
statements to calculate the result of the function. An expres-
sion of the form
return (expression)
returns the value of expression as the result of the function.
The parentheses around the expression are optional.
To activate the subprogram you use a function call. This has the
form
name(expression[,expression] ...)
where name is the name of the function, and the expressions are
argument values for the function. A function call can be used
anywhere you might use any other expression. The value of the
function call is the value that the function returns. For
example, with the function f_to_c() described earlier, f_to_c(41)
has the value 5 (since 41 Fahrenheit is equivalent to 5 Celsius).
The general form of a function definition is
define name([parameter][,parameter]...) {
auto local, local, ...
statement
...
}
The parameters on the first line may be variable names or array
names. Array names are indicated by putting square brackets
after them. For example, if cmpvec() is a function that compares
two vectors, the function definition might start with
define cmpvec(a[],b[]) {
Parameters do not conflict with arrays or variables of the same
name. For example, you may have a parameter named a inside a
function, and a variable named a outside, and the two are consid-
ered entirely separate entities. Assigning a value to the vari-
able does not change the parameter and vice versa. All parame-
ters are passed by value. This means that a copy is made of the
argument value and is assigned to the formal parameter. This
13
bc(1) MPE/iX Shell and Utilities bc(1)
______________________________________________________________________
also applies to arrays. If you pass an array to a function, a
copy is made of the whole array, so any changes made to the array
parameter don't affect the original array.
A function may not need any arguments. In this case, the define
line does not have any parameters inside the parentheses, as in
define f() {
The auto statement declares a sequence of local variables. When
a variable or array name appears in an auto statement, the cur-
rent values of those items are saved and the items are initial-
ized to zero. For the duration of the function, the items have
their new values. When the function terminates, the old values
of the items are restored. Note, however, that bc uses dynamic
scoping rules, unlike C which uses lexical scoping rules (see the
NOTES section for more details).
For example,
define addarr(a[],l) {
auto i, s
for (i=0; i < l; ++i) s += a[i]
return (s)
}
is a function that adds the elements in an array. The argument l
stands for the number of elements in the array. The function
uses two local names: a variable named i and a variable named s.
These variables are local to the function addarr() and are unre-
lated to objects of the same name outside the function (or in
other functions). Objects named in an auto statement are called
autos. Autos are initialized to zero each time the function is
called. Thus the sum s is set to zero each time this function is
called. You may also have local arrays, which are specified by
placing square brackets after the array name in the auto state-
ment.
define func_with_local_array() {
auto local_array[];
for(i=0; i<100; i++) local_array[i] = i*2
}
This example defines a local array called local_array. Local
arrays start out with no elements in them.
If a function refers to an object that is not a parameter and not
declared auto, the object is assumed to be external. External
objects may be referred to by other functions or by statements
which are outside of functions. For example,
14
bc(1) MPE/iX Shell and Utilities bc(1)
______________________________________________________________________
define sum_c(a[],b[],l) {
auto i
for (i=0; i < l; ++i) c[i] = a[i] + b[i]
}
references an external array named c which is the element-by-ele-
ment sum of two other arrays. If c did not exist prior to cal-
ling sum_c(), it is created dynamically. Once the program has
called sum_c(), statements in the program or in functions can
refer to array c.
Functions usually require a return statement. This has the form
return (expression)
The expression is evaluated and used as the result of the func-
tion. The expression must have a single numeric value; it cannot
be an array.
A return statement terminates a function, even if there are more
statements left in the function. For example,
define abs(i) {
if (i < 0) return (-i)
return (i)
}
is a function that returns the absolute value of its argument.
If i is less than zero, the function takes the first return;
otherwise, it takes the second.
A function can also terminate by performing the last statement in
the function. If so, the result of the function is zero. The
function sum_c() is an example of a function that doesn't have a
return statement. The function doesn't need a return statement,
because its work is to calculate the external array c, not to
calculate a single value. Finally, if you want to return from a
function, but not return a value you may use
return ()
or simply
return
If there are no parameters to the return statement, a default
value of zero is returned.
Built-In Functions
bc has a number of built-in functions that perform various opera-
tions. These functions are similar to user-defined functions
with the exception that you don't have to define them yourself
-- they are already set up for you. These functions are:
15
bc(1) MPE/iX Shell and Utilities bc(1)
______________________________________________________________________
length(expression)
calculates the total number of decimal digits in expression.
This includes digits both before and after the decimal point.
The result of length() is an integer. For example,
length(123.456) returns 6.
scale(expression)
returns the scale of expression. For example, scale(123.456)
returns 3. The result of scale() is always an integer. Sub-
tracting the scale of a number from the length of a number
lets you determine the number of digits before the decimal
point.
sqrt(expression)
calculates the square root of the value of expression. The
result is truncated in the least significant decimal place
(not rounded). The scale of the result is the scale of
expression, or the value of scale(), whichever is larger.
You can use the following functions if -l is specified on the
command line. If it is not, the function names are not recog-
nized. There are two names for each function: a full name, and a
single character name for compatibility with POSIX.2. The full
names are the same as the equivalent functions in the standard C
math library.
atan(expression) or a(expression)
calculates the arctangent of expression, returning an angle in
radians.
cos(expression) or c(expression)
calculates the cosine of expression, where expression is an
angle in radians.
exp(expression) or e(expression)
calculates the exponential of expression (that is, the value e
to the power of expression).
jn(integer,expression) or j(integer,expression)
calculates the Bessel function of expression, with order inte-
ger.
log(expression) or l(expression)
calculates the natural logarithm of expression.
sin(expression) or s(expression)
calculates the sine of expression, where expression is an
angle in radians.
EXAMPLES
This sections provides some examples of how to use the bc lan-
guage to accomplish various things.
16
bc(1) MPE/iX Shell and Utilities bc(1)
______________________________________________________________________
Here is a simple function to calculate the sales tax on a pur-
chase. The amount of the purchase is given by purchase, and the
amount of the sales tax (in per cent) is given by tax.
define sales_tax(purchase,tax) {
auto old_scale
scale = 2
tax = purchase*(tax/100)
scale = old_scale
return (tax)
}
For example,
sales_tax(23.99,6)
calculates 6% tax on a purchase of $23.99. The function tempo-
rarily sets the scale value to 2 so that the monetary figures
have two figures after the decimal point. Remember that bc trun-
cates calculations instead of rounding, so some accuracy may be
lost. It is better to use one more digit than needed and perform
the rounding at the end. The round2() function, shown later in
this section, rounds a number to two decimal places.
Division resets the scale of a number to the value of scale.
This can be used as follows to extract the integer portion of a
number.
define integer_part(x) {
# a local to save the value of scale
auto old_scale
# save the old scale, and set scale to 0
old_scale = scale; scale=0
# divide by 1 to truncate the number
x /= 1
# restore the old scale
scale=old_scale
return (x)
}
Having defined this function, it is now trivial to define one to
return the fractional part of a number.
define fractional_part(x) {
return (x - integer_part(x))
}
The following function lets you set the scale of a number to a
given number of decimal places.
17
bc(1) MPE/iX Shell and Utilities bc(1)
______________________________________________________________________
define set_scale(x, s) {
auto os
os = scale
scale = s
x /= 1
scale = os
return (x)
}
set_scale() can now be used in a function which rounds a number
to two decimal places.
define round2(num) {
auto temp;
if(scale(num) < 2) return (set_scale(num, 2))
temp = (num - set_scale(num, 2)) * 1000
if(temp > 5) num += 0.01
return (set_scale(num,2))
}
This is a very useful function if you want to work with monetary
values. For example, you can now rewrite sales_tax() to use
round2().
define sales_tax(purchase,tax) {
auto old_scale
scale = 2
tax = round2(purchase*(tax/100))
scale = old_scale
return (tax)
}
Here is a function which recursively calculates the factorial of
its argument.
define fact (x) {
if(x < 1) return 1
return (x*fact(x-1))
}
The factorial function can also be written iteratively as:
define fact (x) {
auto result
result = 1
while(x>1) result *= x--
return (result)
}
With either version, fact(6) returns 720.
Here is another recursive function. This one calculates the nth
18
bc(1) MPE/iX Shell and Utilities bc(1)
______________________________________________________________________
element of the Fibonacci sequence.
define fib(n) {
if(n < 3) {
return (1)
} else {
return (fib(n-1)+fib(n-2))
}
}
FILES
bc uses the following file:
/usr/lib/lib.b
File containing the library of functions loaded with -l.
DIAGNOSTICS
Possible exit status values are:
0 Successful completion.
1 An error occurred.
Messages
Message: break statement found outside of loop
Cause: bc encountered a break statement when it was not per-
forming a for or while loop.
Action: Make sure that all break statements occur within for or
while loops.
Message: built-in var can't be used as a parameter or auto vari-
able
Cause: You attempted to use the built-in variable var as a
parameter or auto variable.
Action: Do not use built-in variables as parameters or auto
variables.
Message: can't pass array to 'var'
Cause: You attempted to pass an array to the scalar variable
var.
Action: Make sure that the value which you pass to a scalar
variable is a scalar.
Message: can't pass scalar to 'var[]'
Cause: You attempted to pass a scalar to the array var[].
Action: Make sure that the value which you pass to an array
variable is an array.
Message: divide by 0
Cause: You attempted to divide by 0.
Action: Do not divide by 0.
19
bc(1) MPE/iX Shell and Utilities bc(1)
______________________________________________________________________
Message: end of file in comment starting on line num of filename
Cause: bc encountered the end-of-file character when reading a
comment which begins on line num of the file filename.
Action: Make sure that the file filename contains a /* to end
each comment begun with a */.
Message: end of file in string starting on line num of filename
Cause: bc encountered the end-of-file character when reading a
string which begins on line num of the file filename.
Action: Make sure that the file filename contains a " to end
each string.
Message: exponent must be an integer from 0 to number.
Cause: You specified an exponent that was not an integer in
the range 0 to SHRT_MAX-1.
Action: Specify an exponent in the valid range.
Message: filename: system error
Cause: See syserror(3).
Action: See syserror(3).
Message: funcname() is not a function
Cause: You attempted to use a name that is not defined as a
function in a function context.
Action: Specify a valid function name.
Message: numerical constant is too long
Cause: You specified a numerical constant that was longer than
the maximum permitted length, as defined by the value
of the configuration variable BC_STRING_MAX.
Action: Specify a shorter numerical constant.
Message: L?
Cause: You tried to pop a value off of an empty stack variable
using the L operator.
Action: Correct your program.
Message: out of memory
Cause: bc ran out of system resources while trying to allocate
space. If bc is being run interactively, it tries to
free up more resources and returns to the top level of
the interpreter.
Action: Free up some resources and try again. Pay particular
attention to large arrays.
Message: out of memory (fatal)
Cause: bc ran out of system resources but was unable to
recover sufficient storage to continue.
Action: Free up some resources and try again. Pay particular
attention to large arrays.
20
bc(1) MPE/iX Shell and Utilities bc(1)
______________________________________________________________________
Message: Q?
Cause: You specified a string argument to the Q command. This
is invalid. The Q command requires a numeric argument.
Action: Correct your program.
Message: shell command failed to execute
Cause: You specified the sh statement with command as its
argument and bc failed to run command.
Action: Check the syntax of the specified command.
Message: sqrt of negative number
Cause: You attempted to take the square root of a negative
number.
Action: Only use the sqrt function with positive numbers.
Message: string is too long
Cause: You specified a string that was longer than the maximum
permitted length, as defined by the value of the confi-
guration variable BC_STRING_MAX.
Action: Specify a shorter string.
Message: syntax error
Cause: A syntax error was found.
Action: Correct the syntax error.
Message: Unknown option "-option"
Cause: You specified an option that is not valid for bc.
Action: Check the DESCRIPTION section for a list of valid bc
options.
Message: valid array index is 0 through num
Cause: You specified an array index that was not in the range
0 to BC_DIM_MAX-1, where BC_DIM_MAX is a configuration
variable indicating the maximum number of elements that
a bc array may have.
Action: Specify an array index in the indicated range.
Message: 'var' can only have values from num1 through num2
Cause: You attempted to assign a value to the variable var
that was not in the range num1 to num2.
Action: Only assign values in the range num1 to num2 to the
variable var.
Message: warning: body of if/else statement is empty
Cause: You did not supply any statements for the body of an if
or if/else construct. bc only generates this message
when you have specified the -i option.
Action: Make sure that this is what you intended. Check the
DESCRIPTION section for a discussion of bc syntax.
Message: warning: '=-' operator assumed
Cause: This version of bc permits the use of the old style
assignment operators like =- rather than -=. This can
21
bc(1) MPE/iX Shell and Utilities bc(1)
______________________________________________________________________
be ambiguous since a=-2 can mean a =- 2 or a = -2.
Action: Use spaces to clarify the syntax of the expression.
PORTABILITY
POSIX.2. x/OPEN Portability Guide 4.0. All UNIX systems.
The -i option, the && and || operators, the if ... else ...
statement, the print statement, the sh statement, and the
optional parentheses in the return statement are extensions to
the POSIX standard.
NOTES
This section describes some additional details about bc that may
be useful to know.
Unlike the C language which uses lexical scoping rules, bc uses
dynamic scoping. This is most easily explained with an example:
a=10
define f1() {
auto a;
a = 13;
return (f2())
}
define f2() {
return (a)
}
f1()
13
f2()
10
If f1() is called, bc displays the number 13, instead of the num-
ber 10. This is because f1() hides away the old (global) value
of a and then sets it to 13. When f2() refers to a it sees the
variable dynamically created by f1() and so displays 13. When
f1() returns, it restores the old value of a. When f2() is
called directly, instead of through f1() it sees the global value
for a and displays 10. The corresponding C code displays 10 in
both cases.
Numbers are stored as strings in the program and converted into
numbers each time they are used. This is important because the
value of a constant number may change depending on the setting of
the ibase variable. For example, suppose the following instruc-
tions are given to bc:
define ten() {
return (10)
}
ten()
10
22
bc(1) MPE/iX Shell and Utilities bc(1)
______________________________________________________________________
ibase=16
ten()
16
In this example, when the base is set to 10, ten() returns the
decimal value 10; however, when the input base is changed to 16,
the function returns the decimal value 16. This can be a source
of confusing errors in bc programs.
Finally, the library of functions loaded using the -l option is
stored in the file
/usr/lib/lib.b
under your root directory. This is a simple text file which you
can examine and change to add new functions as desired.
MPE/iX NOTES
For information on how the current MPE/iX implementation may
affect the operation of this utility, see Appendix A, MPE/iX
Implementation Considerations.
SEE ALSO
dc(1)
23