Bc programming language
Encyclopedia
bc, for bench calculator, is "an arbitrary precision
Arbitrary-precision arithmetic
In computer science, arbitrary-precision arithmetic indicates that calculations are performed on numbers whose digits of precision are limited only by the available memory of the host system. This contrasts with the faster fixed-precision arithmetic found in most ALU hardware, which typically...

 calculator language
" with syntax similar to the C programming language
C (programming language)
C is a general-purpose computer programming language developed between 1969 and 1973 by Dennis Ritchie at the Bell Telephone Laboratories for use with the Unix operating system....

. bc is typically used as either a mathematical scripting language or as an interactive mathematical shell.

A typical interactive usage is typing the command bc on a Unix
Unix
Unix is a multitasking, multi-user computer operating system originally developed in 1969 by a group of AT&T employees at Bell Labs, including Ken Thompson, Dennis Ritchie, Brian Kernighan, Douglas McIlroy, and Joe Ossanna...

 command prompt and entering a mathematical expression, such as (1 + 3) * 2, whereupon 8 will be output. While bc can work with arbitrary precision, it actually defaults to zero digits after the decimal point - so the expression 2/3 yields 0. This can surprise new bc users unaware of this fact. The "-l" option to bc sets the default scale (digits after the decimal point) to 20, and adds several additional mathematical functions to the language.

Bc first appeared in Version 6 Unix
Version 6 Unix
Sixth Edition Unix, also called Version 6 Unix or just V6, was the first version of the Unix operating system to see wide release outside Bell Labs. It was released in May 1975 and, like its direct predecessor, targeted the DEC PDP-11 family of minicomputers...

 in 1975, and was written by Robert Morris
Robert Morris (cryptographer)
Robert Morris , was an American cryptographer and computer scientist. -Family and Education:Morris was born in Boston, Massachusetts. His parents were Walter W. Morris, a salesman, and Helen Kelly Morris...

 and Lorinda Cherry
Lorinda Cherry
Lorinda Cherry is a computer programmer. She joined Unix in 1972 as an assembly language programmer. She received her Masters in computer science from Stevens Institute of Technology in 1969....

 of Bell Labs
Bell Labs
Bell Laboratories is the research and development subsidiary of the French-owned Alcatel-Lucent and previously of the American Telephone & Telegraph Company , half-owned through its Western Electric manufacturing subsidiary.Bell Laboratories operates its...

. Bc was preceded by dc, an earlier arbitrary precision calculator written by the same authors. Dc could do arbitrary-precision calculations, but its reverse polish notation
Reverse Polish notation
Reverse Polish notation is a mathematical notation wherein every operator follows all of its operands, in contrast to Polish notation, which puts the operator in the prefix position. It is also known as Postfix notation and is parenthesis-free as long as operator arities are fixed...

 syntax was inconvenient for users, and therefore Bc was written as a front-end to Dc. Bc was a very simple compiler
Compiler
A compiler is a computer program that transforms source code written in a programming language into another computer language...

 (a single yacc
Yacc
The computer program yacc is a parser generator developed by Stephen C. Johnson at AT&T for the Unix operating system. The name is an acronym for "Yet Another Compiler Compiler." It generates a parser based on an analytic grammar written in a notation similar to BNF.Yacc used to be available as...

 source file with a few hundreds lines) which converted the new, C-like, bc syntax into dc's reverse polish notation, and piped the results through dc.

In 1991, POSIX
POSIX
POSIX , an acronym for "Portable Operating System Interface", is a family of standards specified by the IEEE for maintaining compatibility between operating systems...

 rigorously defined and standardized bc. Two implementations of this standard survive today: The first is the traditional Unix implementation, a front-end to dc, which survives in Unix and Plan 9
Plan 9 from Bell Labs
Plan 9 from Bell Labs is a distributed operating system. It was developed primarily for research purposes as the successor to Unix by the Computing Sciences Research Center at Bell Labs between the mid-1980s and 2002...

 systems. The second is the free software
Free software
Free software, software libre or libre software is software that can be used, studied, and modified without restriction, and which can be copied and redistributed in modified or unmodified form either without restriction, or with restrictions that only ensure that further recipients can also do...

 GNU
GNU
GNU is a Unix-like computer operating system developed by the GNU project, ultimately aiming to be a "complete Unix-compatible software system"...

 bc, first released in 1991 by Philip A. Nelson. The GNU implementation has numerous extensions beyond the POSIX standard, and is no longer a front-end to dc (it is a bytecode interpreter).

POSIX bc

The POSIX standardized bc language is traditionally written as a program in the dc programming language to provide a higher level of access to the features of the dc language without the complexities of dc's terse syntax.

In this form, the bc language contains single letter variable
Variable (programming)
In computer programming, a variable is a symbolic name given to some known or unknown quantity or information, for the purpose of allowing the name to be used independently of the information it represents...

, array and function names and most standard arithmetic operators as well as the familiar control flow
Control flow
In computer science, control flow refers to the order in which the individual statements, instructions, or function calls of an imperative or a declarative program are executed or evaluated....

 constructs, (if(cond)..., while(cond)... and for(init;cond;inc)...) from C. Unlike C, an if clause may not be followed by an else.

Functions are defined using a define keyword and values are returned from them using a return followed by the return value in parentheses. The auto keyword (optional in C) is used to declare a variable as local to a function.

All numbers and variable contents are arbitrary precision numbers whose precision (in decimal places) is determined by the global scale variable.

The numeric base of input (in interactive mode), output and program constants may be specified by setting the reserved ibase (input base) and obase (output base) variables.

Output is generated by deliberately not assigning the result of a calculation to a variable.

Comments may be added to bc code by use of the C /* and */ (start and end comment) symbols.

Exactly as C

The following POSIX bc operators
Operator (programming)
Programming languages typically support a set of operators: operations which differ from the language's functions in calling syntax and/or argument passing mode. Common examples that differ by syntax are mathematical arithmetic operations, e.g...

 behave exactly like their C counterparts:

+ - * /

+= -= *= /=

++ -- < >

!= <= >=

[ ] { }

Similar to C

The modulus operators:

% %=

... behave exactly like their C counterparts only when the global scale variable is set to 0, i.e. all calculations are integer-only. When scale is greater than 0 the modulus is calculated relative to the smallest positive value greater than zero.

Only resembling C

The operators:

^ ^=

... resemble the C bitwise exclusive-or operators, but are in fact the bc integer exponentiation operators.

'Missing' operators relative to C

The bitwise
Bitwise operation
A bitwise operation operates on one or more bit patterns or binary numerals at the level of their individual bits. This is used directly at the digital hardware level as well as in microcode, machine code and certain kinds of high level languages...

, boolean
Boolean logic
Boolean algebra is a logical calculus of truth values, developed by George Boole in the 1840s. It resembles the algebra of real numbers, but with the numeric operations of multiplication xy, addition x + y, and negation −x replaced by the respective logical operations of...

 and conditional operators:

& | ^ && ||

&= |= ^= &&= ||=

<< >>

<<= >>=

?:

... are not available in POSIX bc.

Built-in functions

The sqrt function for calculating square root
Square root
In mathematics, a square root of a number x is a number r such that r2 = x, or, in other words, a number r whose square is x...

s is POSIX bc's only built-in mathematical function. Other functions are available in an external standard library.

The scale function for determining the precision (as with the scale variable) of its argument and the length function for determining the number of significant decimal digits in its argument are also built-in.

Standard library functions

bc's standard math library (defined with the -l option) contains functions for calculating sine
Sine
In mathematics, the sine function is a function of an angle. In a right triangle, sine gives the ratio of the length of the side opposite to an angle to the length of the hypotenuse.Sine is usually listed first amongst the trigonometric functions....

, cosine, arctangent, natural logarithm
Natural logarithm
The natural logarithm is the logarithm to the base e, where e is an irrational and transcendental constant approximately equal to 2.718281828...

, the exponential function
Exponential function
In mathematics, the exponential function is the function ex, where e is the number such that the function ex is its own derivative. The exponential function is used to model a relationship in which a constant change in the independent variable gives the same proportional change In mathematics,...

 and the two parameter Bessel function
Bessel function
In mathematics, Bessel functions, first defined by the mathematician Daniel Bernoulli and generalized by Friedrich Bessel, are canonical solutions y of Bessel's differential equation:...

 J. Most standard mathematical functions (including the other inverse trigonometric functions) can be constructed using these. See external links for implementations of many other functions.

The -l option changes the scale to 20 (source), so things such as modulo may work unexpectedly. For example, write "bc -l" and then the command "print 3%2" outputs 0, instead of 1. But if you do it like "bc -l", "scale=0" and then the command "print 3%2" has 1 as output.
Plan 9 bc


Plan 9 bc is just like POSIX bc but for an additional print statement.

GNU bc
GNU bc derives from the POSIX standard and includes many enhancements. It is entirely separate from dc-based implementations of the POSIX standard and is instead written in C. Nevertheless, it is fully backwards compatible as all POSIX bc programs will run unmodified as GNU bc programs.

GNU bc variables, arrays and function names may contain more than one character, some more operators have been included from C, and notably, an if clause may be followed by an else.

Output is achieved either by deliberately not assigning a result of a calculation to a variable (the POSIX way) or by using the added print statement.

Furthermore, a read statement allows the interactive input of a number into a running calculation.

In addition to C-style comments, a # character will cause everything after it until the next new-line to be ignored.

The value of the last calculation is always stored within the additional built-in last variable.

Extra operators

The following logical operators are additional to those in POSIX bc:

&& || !

... and are available for use in conditional statements (such as within an if statement). Note, however, that there are still no equivalent bitwise or assignment operations.

Functions

All functions available in GNU bc are inherited from POSIX. No further functions are provided as standard with the GNU distribution.
Example code
Since the bc ^ operator only allows an integer power to its right, one of the first functions a bc user might write is a power function with a floating point exponent. Both of the below assume the standard library has been included:

A 'Power' function in POSIX bc

/* A function to return the integer part of x */
define i(x) {
auto s
s = scale
scale = 0
x /= 1 /* round x down */
scale = s
return (x)
}

/* Use the fact that x^y e^(y*log(x)) */
define p(x,y) {
if (y i(y)) {
return (x ^ y)
}
return ( e( y * l(x) ) )
}

An equivalent 'Power' function in GNU bc

# A function to return the integer part of a number
define int(number) {
auto oldscale
oldscale = scale
scale = 0
number /= 1 /* round number down */
scale = oldscale
return number
}

# Use the fact that number^exponent e^(exponent*log(number))
define power(number,exponent) {
if (exponent

int(exponent)) {
return number ^ exponent
} else {
return e( exponent * l(number) )
}
}

Calculating Pi to 10000 places (using the K. Takano equation (1982))


a(phi) returns the arctangent of phi

$ bc -l -q
scale = 10000;
4*(12*a(1/49) + 32*a(1/57) - 5*a(1/239) + 12*a(1/110443))

Calculating Pi to 100000 places using atan


the atan of 1 is 45 degrees, which is pi/4 in radians
$ bc -l
scale=100000
4*a(1)
# If you have a slow computer this may take some time.

A translated C function
Because the syntax of bc is very similar to that of C
C (programming language)
C is a general-purpose computer programming language developed between 1969 and 1973 by Dennis Ritchie at the Bell Telephone Laboratories for use with the Unix operating system....

, published algorithms written in C can often be translated into BC quite easily, which immediately provides the arbitrary precision of BC. For example, in the Journal of Statistical Software
Journal of Statistical Software
The Journal of Statistical Software is a peer-reviewed open access scientific journal that publishes papers related to statistical software...

 (July 2004, Volume 11, Issue 5), George Marsaglia
George Marsaglia
George Marsaglia was an American mathematician and computer scientist. He established the lattice structure of congruential random number generators in the paper "Random numbers fall mainly in the planes". This phenomenon is sometimes called the Marsaglia effect...

 published the following C code for the cumulative normal distribution:


double Phi(double x)
{
long double s=x,t=0,b=x,q=x*x,i=1;
while(s!=t)
s=(t=s)+(b*=q/(i+=2));
return .5+s*exp(-.5*q-.91893853320467274178L);
}


With a few minutes of work, this can be translated to the following GNU bc code:


define normal(x)
{
auto s,t,b,q,i,const;
const=0.5*l(8*a(1));
s=x;
t=0;
b=x;
q=x*x;
i=1;
while(s!=t) {s=(t=s)+(b*=q/(i+=2))};
return .5+s*e(-.5*q-const);
}

Using bc in shell scripts
bc can be used non-interactively, with input via a pipe
Pipeline (Unix)
In Unix-like computer operating systems , a pipeline is the original software pipeline: a set of processes chained by their standard streams, so that the output of each process feeds directly as input to the next one. Each connection is implemented by an anonymous pipe...

. This is useful inside shell script
Shell script
A shell script is a script written for the shell, or command line interpreter, of an operating system. It is often considered a simple domain-specific programming language...

s. For example:
$ result=$(echo "scale=2; 5 * 7 / 3;" | bc)
$ echo $result
11.66

In contrast, note that the bash shell only performs integer arithmetic, e.g.:
$ result=$((5 * 7 /3))
$ echo $result
11
See also

  • dc programming language
  • C programming language
    C (programming language)
    C is a general-purpose computer programming language developed between 1969 and 1973 by Dennis Ritchie at the Bell Telephone Laboratories for use with the Unix operating system....

  • hoc programming language
    Hoc (programming language)
    hoc, an acronym for High Order Calculator, is an interpreted programming language that was used in the 1984 book The Unix Programming Environment to demonstrate how to build interpreters using Yacc....


External links
The source of this article is wikipedia, the free encyclopedia.  The text of this article is licensed under the GFDL.
 
x
OK