basic interactive calculator

from the OS shell


$> bc -ql <<<"2^16"
65536

$> bc -ql
define power (basis, exponenta) {
  e (exponenta * l (basis))
}
power (10.7 , 2.3)
233.12169314020004392304
0
    
$> bc<<<2+4*17
$> 70
$> echo "4+2*17" | bc
$> 38

$> bc myfile.bc

$> bc myfile.dat myfile.bc

a standard math library is available by command line option

  bc -l

bc starts by processing code from all the files listed on the command line in the order listed

after all files have been processed, bc reads from the standard input

all code is executed as it is read

if a file contains a command halt then bc will never read from the standard input

input numbers may contain the characters 0-9 and A-F. (note: they must be capitals)

comments

comments start with the characters /* and end with the characters */
these comments include any newlines (EOL)

to support the use of scripts for bc, a single line comment has been added as an extension, which starts with # character

options

-i, --interactive
force interactive mode
-l, --mathlib
define the standard math library
-w, --warn
give warnings for extensions to POSIX bc
-s, --standard
process exactly the POSIX bc language
-q, --quiet
do not print the normal GNU bc welcome

numbers

numbers are arbitrary precision numbers
there are two attributes of numbers, the length and the scale
the length is the total number of significant decimal digits in a number
the scale is the total number of decimal digits after the decimal point

variables

numbers are stored in two types of variables, simple variables and arrays

names begin with a letter followed by any number of letters, digits and underscores. all letters must be lower case
array variable name will be followed by brackets [ ]

there are four special variables: scale, ibase, obase, and last

scale
digits after the decimal point. 0 by default

ibase and obase
conversion base for input and output numbers. default is base 10
the legal values of ibase are 2 through 16

last
a variable that has the value of the last printed number
POSIX bc does not have a last variable

expressions

- expr
the negation of the expression

++ var
-- var
var ++
var --

expr + expr
expr - expr
expr * expr
expr / expr
expr % expr
expr ^ expr
the second expression must be an integer. (if the second expression is not an integer, a warning is generated and the expression is truncated to get an integer value). the scale of the result is scale if the exponent is negative. If the exponent is positive scale(a^b) = min(scale(a)*b, max(scale, scale(a))

relational expressions are always evaluate to 0 or 1, 0 if the relation is false and 1 if the relation is true. POSIX bc requires that relational expressions are used only in if, while, and for statements and that only one relational test may be done in them
expr1 < expr2
expr1 <= expr2
expr1 > expr2
expr1 >= expr2
expr1 == expr2
expr1 != expr2

boolean operations (extension) are also legal. the result of all boolean operations are 0 and 1

!expr
expr && expr
expr || expr

the expression precedence is as follows: (lowest to highest)

|| left associative
&& left associative
! nonassociative
relational operators left associative
assignment operator right associative
+ - left associative
* / % left associative
^ right associative
- (unary) nonassociative
++ -- nonassociative

there are a few more special expressions that are provided in bc:

read ( )
the read function (an extension) will read a number from the standard input, regardless of where the function occurs. beware, this can cause problems with the mixing of data and program in the standard input. the value of the read function is the number read from the standard input using the current value of the variable ibase for the conversion base

sqrt ( expression )
if the expression is negative, a run time error is generated

statements

in bc statements are executed "as soon as possible." execution happens when a newline in encountered and there is one or more complete statements. in fact, both a semicolon and a newline are used as statement separators. an improperly placed newline will cause a syntax error
if the expression starts with "variable = ...", it is considered to be an assignment statement
if the expression is not an assignment statement, the expression is evaluated and printed to the output. after the number is printed, a newline is printed

due to the interactive nature of bc, printing a number causes the side effect of assigning the printed value to the special variable last. assigning to last is legal and will overwrite the last printed value with the assigned value

if the expression is string then the string is printed to the output. strings start with a double quote character and contain all characters until the next double quote character. no newline character is printed after the string

print <list>
the "list" is a list of strings and expressions separated by commas. no terminating newline is printed. strings in the print statement are printed to the output and may contain special characters. special characters start with the backslash character (\). the special characters recognized by bc are "a" (alert or bell), "b" (backspace), "f" (form feed), "n" (newline), "r" (carriage return), "q" (double quote), "t" (tab), and "\" (backslash)

{ statement_list }
this is the compound statement. it allows multiple statements to be grouped together for execution

if (expression) statement1 [else statement2]
the else clause is an extension

while (expression) statement
termination of the loop is caused by a zero expression value or the execution of a break statement

for ([expression1]; [expression2]; [expression3]) statement
if expression1 or expression3 are missing, nothing is evaluated at the point they would be evaluated. if expression2 is missing, it is the same as substituting the value 1 for expression2. (POSIX bc requires all three expressions)

break
this statement causes a forced exit of the most recent enclosing while statement or for statement

continue
the continue statement (an extension) causes the most recent enclosing for statement to start the next iteration

halt
the halt statement (an extension) is an executed statement that causes the bc processor to quit only when it is executed

return
return the value 0 from a function

return ( expression )
return the value of the expression from a function. as an extension, the parenthesis are not required

quit
when the quit statement is read, the bc processor is terminated, regardless of where the quit statement is found

functions

function definitions are "dynamic" in the sense that a function is undefined until a definition is encountered in the input. that definition is then used until another definition function for the same name is encountered. the new definition then replaces the older definition

a function is defined as follows:

 define name (parameters_list) {
   auto_list 
   statement_list
 }
a function call is just an expression of the form "name(parameters)"

parameters are numbers or arrays (an extension)

in the function definition, zero or more parameters are defined by listing their names separated by commas

all parameters are call by value. arrays are specified in the parameter definition by the notation "name[]"

in the function call, actual parameters are full expressions for number parameters. the same notation is used for passing arrays as for defining array parameters. the named array is passed by value to the function. parameter numbers and types are checked when a function is called. any mismatch in number or types of parameters will cause a runtime error

the auto_list is an optional list of variables that are for "local" use. these variables have their values pushed onto a stack at the start of the function. the variables are then initialized to zero and used throughout the execution of the function. at function exit, these variables are popped so that the original value (at the time of the function call) of these variables are restored

auto variables are different than traditional local variables because if function A calls function B, B may access function A's auto variables by just using the same name, unless function B has called them auto variables. Due to the fact that auto variables and parameters are pushed onto a stack, bc supports recursive functions

there are two versions of the return statement. the first form, "return", returns the value 0 to the calling expression. the second form, "return ( expression )", computes the value of the expression and returns that value to the calling expression. there is an implied "return (0)" at the end of every function

the standard requires the opening brace be on the same line as the define keyword and all other parts must be on following lines. optional will allow any number of newlines before and after the opening brace of the function. for example, the following definitions are legal:

 define d (n) { return (2*n); }

 define d (n)
 { return (2*n); }
functions may be defined as void. a void funtion returns no value. a void function does not produce any output when called by itself on an input line. the keyword void is placed between the key word define and the function name. example:
 define py (y) { print "--->", y, "<---"; }
 py (1)
 --->1<---0

since py is not a void function, the call of py (1) prints the desired output and then prints the value of the function. since the function is not given an explicit return statement, it is zero, sothe zero is printed

 define void px (x) { print "--->", x, "<---"; }
 px (1)
 --->1<---

now no zero is printed because the function is a void function

to declare a call by variable array, the declaration of the array parameter in the function definition looks like "*name[]". the call to the function remains the same as call by value arrays

names
traditional and POSIX bc have single letter names for functions, variables and arrays. they have been extended to be multi-character names that start with a letter and may contain letters, numbers and the underscore character

POSIX

&&, ||, !
POSIX bc does not have logical operators

read
POSIX bc does not have a read function

print
POSIX bc does not have a print statement

continue
POSIX bc does not have a continue statement

return
POSIX bc requires parentheses around the return expression

array parameters
POSIX bc does not support array parameters in full. the POSIX grammar allows for arrays in function definitions, but does not provide a method to specify an array as an actual parameter

function format
POSIX bc requires the opening brace on the same line as the define keyword and the auto statement on the next line

=+, =-, =*, =/, =%, =^
POSIX bc does not require these "old style" assignment operators to be defined

math library

if bc is invoked with the -l option, a math library is preloaded and the default scale is set to 20. the math library defines the following functions:

s (x) sine of x, x is in radians
c (x) cosine of x, x is in radians
a (x) arctangent of x, returns radians
l (x) natural logarithm of x
e (x) raising e to the value x
j (n, x) Bessel function of integer order n of x

ENVIRONMENT VARIABLES

the following environment variables are processed by bc:

POSIXLY_CORRECT
this is the same as the -s option

BC_ENV_ARGS
this is another mechanism to get arguments to bc

the format is the same as the command line arguments. these arguments are processed first, so any files listed in the environment arguments are processed before any command line argument files

this allows the user to set up "standard" options and files to be processed at every invocation of bc

BC_LINE_LENGTH
this should be an integer specifying the number of characters in an output line for numbers

this includes the backslash and newline characters for long numbers. as an extension, the value of zero disables the multi-line feature. any other value of this variable that is less than 3 sets the line length to 70

EXAMPLE

/* input data:
     random variables  x[i]
     probabilities     p[i]
     size of arrays    n
   read data from std input  */

scale = 3

define expectation () {
  auto i
  # change the global variable y here. caution!
  y = 0
  # x[] and p[] - are global variables. should be defined till this point
  while (i < n) { y += (p[i] * x[i]); i += 1 }
  return y
}

define sigma () {
  auto i 
  # use global variable y here. shoul be valid till this monent
  # changes the global variable x[]. caution!
  while (i < n) { x[i] = (x[i] - y) ^ 2; i += 1 }
  return sqrt (expectation ())
}

# user input :
print "input size : "
n = read ()
j = 0; while (j < n) { print "x[", j + 1, "] ? "; x[j] = read (); j += 1 }
j = 0; while (j < n) { print "p[", j + 1, "] ? "; p[j] = read (); j += 1 }

# program output :
print "====================\nexpectation : ", expectation () , "\n"
print "sigma       : ", sigma (), "\n====================\n"

quit