MiniUnix/usr/doc/bc/bc
.RP
.TL
BC \- An Arbitrary Precision Desk-Calculator Language
.AU
Lorinda Cherry
.AU
Robert Morris
.AI
.MH
.AB
BC is a language and a compiler for doing arbitrary precision arithmetic
on the PDP-11 under the UNIX time-sharing
system. The output of the compiler is interpreted and executed by
a collection of routines which can input, output, and do
arithmetic on indefinitely large integers and on scaled fixed-point
numbers.
.PP
These routines are themselves based on a dynamic storage allocator.
Overflow does not occur until all available core storage
is exhausted.
.PP
The language has a complete control structure as well as immediate-mode
operation. Functions can be defined and saved for later execution.
.PP
Two five hundred-digit numbers can be multiplied to give a
thousand digit result in about ten seconds.
.PP
A small collection of library functions is also available,
including sin, cos, arctan, log, exponential, and Bessel functions of
integer order.
.PP
Some of the uses of this compiler are
.IP \-
to do computation with large integers,
.IP \-
to do computation accurate to many decimal places,
.IP \-
conversion of numbers from one base to another base.
.AE
.PP
.SH
Introduction
.PP
BC is a language and a compiler for doing arbitrary precision
arithmetic on the UNIX time-sharing system [1].
The compiler was written to make conveniently available a
collection of routines (called DC [6]) which are capable of doing
arithmetic on integers of arbitrary size. The compiler
is by no means intended to provide a complete programming
language.
It is a minimal language facility.
.PP
There is a scaling provision that permits the
use of decimal point notation.
Provision is made for input and output in bases other than
decimal. Numbers can be converted from decimal to octal by
simply setting the output base to equal 8.
.PP
The actual limit on the number of digits that can
be handled depends on the amount of storage available on the machine.
Manipulation of numbers with many hundreds of digits
is possible even on the smallest versions of UNIX.
.PP
The syntax of BC has been deliberately selected to agree
substantially with the C language [2,3]. Those who
are familiar with C will find few surprises in this language.
.SH
Simple Computations with Integers
.PP
The simplest kind of statement is an arithmetic expression
on a line by itself.
For instance, if you type in the line:
.DS
142857 + 285714
.DE
the program responds immediately with the line
.DS
428571
.DE
The operators \-, *, /, %, and ^ can also be used; they
indicate subtraction, multiplication, division, remaindering, and
exponentiation, respectively. Division of integers produces an
integer result truncated toward zero.
Division by zero produces an error
comment.
.PP
Any term in an expression may be prefixed by a minus sign to
indicate that it is to be negated (the `unary' minus sign).
The expression
.DS
7+\-3
.DE
is interpreted to mean that \-3 is to be added to 7.
.PP
More complex expressions with several operators and with
parentheses are interpreted just as in
Fortran, with ^ having the greatest binding
power, then * and % and /, and finally + and \-.
Contents of parentheses are evaluated before material
outside the parentheses.
Exponentiations are
performed from right to left and the other operators
from left to right.
The two expressions
.DS
a^b^c and a^(b^c)
.DE
are equivalent, as are the two expressions
.DS
a*b*c and (a*b)*c
.DE
BC shares with Fortran and C the undesirable convention that
.DS
a/b*c is equivalent to (a/b)*c
.DE
.PP
Internal storage registers to hold numbers have single lower-case
letter names. The value of an expression can be assigned to
a register in the usual way. The statement
.DS
x = x + 3
.DE
has the effect of increasing by three the value of the contents of the
register named x.
When, as in this case, the outermost operator is an =, the
assignment is performed but the result is not printed.
Only 26 of these named storage registers are available.
.PP
There is a built-in square root function whose
result is truncated to an integer (but see scaling below).
The lines
.DS
x = sqrt(191)
x
.DE
produce the printed result
.DS
13
.DE
.SH
Bases
.PP
There are special internal quantities, called `ibase' and `obase'.
The contents of `ibase', initially set to 10,
determines the base used for interpreting numbers read in.
For example, the lines
.DS
ibase = 8
11
.DE
will produce the output line
.DS
9
.DE
and you are all set up to do octal to decimal conversions.
Beware, however of trying to change the input base back
to decimal by typing
.DS
ibase = 10
.DE
Because the number 10 is interpreted as octal, this statement will
have no effect.
For those who deal in hexadecimal notation,
the characters A\-F are permitted in numbers
(no matter what base is in effect)
and are
interpreted as digits having values 10\-15 respectively.
The statement
.DS
ibase = A
.DE
will change you back to decimal input base no matter what the
current input base is.
Negative and large positive input bases are
permitted but useless.
No mechanism has been provided for the input of arbitrary
numbers in bases less than 1 and greater than 16.
.PP
The contents of `obase', initially set to 10, are used as the base for output
numbers. The lines
.DS
obase = 16
1000
.DE
will produce the output line
.DS
3E8
.DE
which is to be interpreted as a 3-digit hexadecimal number.
Very large output bases are permitted, and they are sometimes useful.
For example, large numbers can be output in groups of five digits
by setting `obase' to 100000.
Strange (i.e. 1, 0, or negative) output bases are
handled appropriately.
.PP
Very large numbers are split across lines with 70 characters per line.
Lines which are continued end with \\.
Decimal output conversion is practically instantaneous, but output
of very large numbers (i.e., more than 100 digits) with other bases
is rather slow.
Non-decimal output conversion of
a one hundred digit number takes about
three seconds.
.PP
It is best to remember that `ibase' and `obase' have no effect
whatever on the course of internal computation or
on the evaluation of expressions, but only affect input and
output conversion, respectively.
.SH
Scaling
.PP
A third special internal quantity called `scale' is
used to determine the scale of calculated
quantities.
Numbers may have
up to 99 decimal digits after the decimal point.
This fractional part is retained in further computations.
We refer to the number of digits after the decimal point of
a number as its scale.
.PP
When two scaled numbers are combined by
means of one of the arithmetic operations, the result
has a scale determined by the following rules. For
addition and subtraction, the scale of the result is the larger
of the scales of the two operands. In this case,
there is never any truncation of the result.
For multiplications, the scale of the result is never
less than the maximum of the two scales of the operands,
never more than the sum of the scales of the operands
and, subject to those two restrictions,
the scale of the result is set equal to the contents of the internal
quantity `scale'.
The scale of a quotient is the contents of the internal
quantity `scale'. The scale of a remainder is
the sum of the scales of the quotient and the divisor.
The result of an exponentiation is scaled as if
the implied multiplications were performed.
An exponent must be an integer.
The scale of a square root is set to the maximum of the scale
of the argument and the contents of `scale'.
.PP
All of the internal operations are actually carried out in terms
of integers, with digits being discarded when necessary.
In every case where digits are discarded, truncation and
not rounding is performed.
.PP
The contents of
`scale' must be no greater than
99 and no less than 0. It is initially set to 0.
In case you need more than 99 fraction digits, you may arrange
your own scaling.
.PP
The internal quantities `scale', `ibase', and `obase' can be
used in expressions just like other variables.
The line
.DS
scale = scale + 1
.DE
increases the value of `scale' by one, and the line
.DS
scale
.DE
causes the current value of `scale' to be printed.
.PP
The value of `scale' retains its meaning as a
number of decimal digits to be retained in internal
computation even when `ibase' or `obase' are not equal to 10.
The internal computations (which are still conducted in decimal,
regardless of the bases) are performed to the specified number
of decimal digits, never hexadecimal or octal or any
other kind of digits.
.SH
Functions
.PP
The name of a function is a single lower-case letter.
Function names are permitted to collide with simple
variable names.
Twenty-six different defined functions are permitted
in addition to the twenty-six variable names.
The line
.DS
define a(x){
.DE
begins the definition of a function with one argument.
This line must be followed by one or more statements,
which make up the body of the function, ending
with a right brace }.
Return of control from a function occurs when a return
statement is executed or when the end of the function is reached.
The return statement can take either
of the two forms
.DS
return
return(x)
.DE
In the first case, the value of the function is 0, and in
the second, the value of the expression in parentheses.
.PP
Variables used in the function can be declared as automatic
by a statement of the form
.DS
auto x,y,z
.DE
There can be only one `auto' statement in a function and it must
be the first statement in the definition.
These automatic variables are allocated space and initialized
to zero on entry to the function and thrown away on return. The
values of any variables with the same names outside the function
are not disturbed.
Functions may be called recursively and the automatic variables
at each level of call are protected.
The parameters named in a function definition are treated in
the same way as the automatic variables of that function
with the single exception that they are given a value
on entry to the function.
An example of a function definition is
.DS
define a(x,y){
auto z
z = x*y
return(z)
}
.DE
The value of this function, when called, will be the
product of its
two arguments.
.PP
A function is called by the appearance of its name
followed by a string of arguments enclosed in
parentheses and separated by commas.
The result
is unpredictable if the wrong number of arguments is used.
.PP
Functions with no arguments are defined and called using
parentheses with nothing between them: b().
.PP
If the function
.ft I
a
.ft
above has been defined, then the line
.DS
a(7,3.14)
.DE
would cause the result 21.98 to be printed and the line
.DS
x = a(a(3,4),5)
.DE
would cause the value of x to become 60.
.SH
Subscripted Variables
.PP
A single lower-case letter variable name
followed by an expression in brackets is called a subscripted
variable (an array element).
The variable name is called the array name and the expression
in brackets is called the subscript.
Only one-dimensional arrays are
permitted. The names of arrays are permitted to
collide with the names of simple variables and function names.
Any fractional
part of a subscript is discarded before use.
Subscripts must be greater than or equal to zero and
less than or equal to 2047.
.PP
Subscripted variables may be freely used in expressions, in
function calls, and in return statements.
.PP
An array name may be used as an argument to a function,
or may be declared as automatic in
a function definition by the use of empty brackets:
.DS
f(a[\|])
define f(a[\|])
auto a[\|]
.DE
When an array name is so used, the whole contents of the array
are copied for the use of the function, and thrown away on exit
from the function.
Array names which refer to whole arrays cannot be used
in any other contexts.
.SH
Control Statements
.PP
The `if', the `while', and the `for' statements
may be used to alter the flow within programs or to cause iteration.
The range of each of them is a statement or
a compound statement consisting of a collection of
statements enclosed in braces.
They are written in the following way
.DS
if(relation) statement
while(relation) statement
for(expression1; relation; expression2) statement
.DE
or
.DS
if(relation) {statements}
while(relation) {statements}
for(expression1; relation; expression2) {statements}
.DE
.PP
A relation in one of the control statements is an expression of the form
.DS
x>y
.DE
where two expressions are related by one of the six relational
operators <, >, <=, >=, ==, or !=.
The relation ==
stands for `equal to' and != stands for `not equal to'.
The meaning of the remaining relational operators is
clear.
.PP
BEWARE of using = instead of == in a relational. Unfortunately,
both of them are legal, so you will not get a diagnostic
message, but = really will not do a comparison.
.PP
The `if' statement causes execution of its range
if and only if the relation is true.
Then control passes to the next statement in sequence.
.PP
The `while' statement causes execution of its range
repeatedly as long as the relation
is true. The relation is tested before each execution
of its range and if the relation
is false, control passes to the next statement beyond the range
of the while.
.PP
The `for' statement begins
by executing `expression1'. Then the relation is tested
and, if true, the statements in the range of the `for' are executed.
Then `expression2' is executed. The relation is tested, and so on.
The typical use of the `for' statement is for a controlled iteration,
as in the statement
.DS
for(i=1; i<=10; i=i+1) i
.DE
which will print the integers from 1 to 10.
Here are some examples of the use of the control statements.
.DS
define f(n){
auto i, x
x=1
for(i=1; i<=n; i=i+1) x=x*i
return(x)
}
.DE
The line
.DS
f(a)
.DE
will print
.ft I
a
.ft
factorial if
.ft I
a
.ft
is a positive integer.
Here is the definition of a function which will
compute values of the binomial coefficient
(m and n are assumed to be positive integers).
.DS
define b(n,m){
auto x, j
x=1
for(j=1; j<=m; j=j+1) x=x*(n\-j+1)/j
return(x)
}
.DE
The following function computes values of the exponential function
by summing the appropriate series
without regard for possible truncation errors:
.DS
scale = 20
define e(x){
auto a, b, c, d, n
a = 1
b = 1
c = 1
d = 0
n = 1
while(1==1){
a = a*x
b = b*n
c = c + a/b
n = n + 1
if(c==d) return(c)
d = c
}
}
.DE
.SH
Some Details
.PP
There are some language features that every user should know
about even if he will not use them.
.PP
Normally statements are typed one to a line. It is also permissible
to type several statements on a line separated by semicolons.
.PP
If an assignment statement is parenthesized, it then has
a value and it can be used anywhere that an expression can.
For example, the line
.DS
(x=y+17)
.DE
not only makes the indicated assignment, but also prints the
resulting value.
.PP
Here is an example of a use of the value of an
assignment statement even when it is not parenthesized.
.DS
x = a[i=i+1]
.DE
causes a value to be assigned to x and also increments i
before it is used as a subscript.
.PP
The following constructs work in BC in exactly the same manner
as they do in the C language. Consult the appendix or the
C manuals [2,3] for their exact workings.
.DS
.ta 2i
x=y=z is the same as x=(y=z)
x =+ y x = x+y
x =\- y x = x\-y
x =* y x = x*y
x =/ y x = x/y
x =% y x = x%y
x =^ y x = x^y
x++ (x=x+1)\-1
x\-\- (x=x\-1)+1
++x x = x+1
\-\-x x = x\-1
.DE
Even if you don't intend to use the constructs,
if you type one inadvertently, something correct but unexpected
may happen.
.PP
WARNING! In some of these constructions, spaces are
significant.
There is a real difference between
x=\-y and x= \-y.
The first replaces x by x\-y and the second by \-y.
.SH
Three Important Things
.PP
1. To exit a BC program, type `quit'.
.PP
2. There is a comment convention identical to that of C and
of PL/I. Comments begin with `/*' and end with `*/'.
.PP
3. There is a library of math functions which may be obtained by
typing at command level
.DS
bc \-l
.DE
This command will load a set of library functions
which, at the time of writing, consists of sine (named `s'),
cosine (`c'), arctangent (`a'), natural logarithm (`l'),
exponential (`e') and Bessel functions of integer order (`j(n,x)'). Doubtless more functions will be added
in time.
The library sets the scale to 20. You can reset it to something
else if you like.
The design of these mathematical library routines
is discussed elsewhere [4].
.PP
If you type
.DS
bc file ...
.DE
BC will read and execute the named file or files before accepting
commands from the keyboard. In this way, you may load your
favorite programs and function definitions.
.SH
Acknowledgement
.PP
The compiler is written in YACC [5]; its original
version was written by S. C. Johnson.
.SH
References
.IP[1]
K. Thompson and D. M. Ritchie,
.ft I
UNIX Programmer's Manual,
.ft
Fifth Edition (1974)
.IP[2]
D. M. Ritchie,
.ft I
C Reference Manual,
.ft
.IP[3]
B. W. Kernighan,
.ft I
Programming in C: A Tutorial,
.ft
.IP[4]
Robert Morris,
.ft I
A Library of Reference Standard Mathematical Subroutines,
.ft
.IP[5]
S. C. Johnson,
.ft I
YACC, Yet Another Compiler-Compiler,
.ft
.IP[6]
R. Morris and L. L. Cherry,
.ft I
DC \- An Interactive Desk Calculator,
.ft
.LP