Bc programming language
   HOME

TheInfoList



OR:

bc, for ''basic calculator'' (often referred to as ''bench calculator''), is "''an
arbitrary-precision In computer science, arbitrary-precision arithmetic, also called bignum arithmetic, multiple-precision arithmetic, or sometimes infinite-precision arithmetic, indicates that calculations are performed on numbers whose digits of precision are li ...
calculator language''" with syntax similar to the
C programming language ''The C Programming Language'' (sometimes termed ''K&R'', after its authors' initials) is a computer programming book written by Brian Kernighan and Dennis Ritchie, the latter of whom originally designed and implemented the language, as well a ...
. bc is typically used as either a mathematical scripting language or as an interactive mathematical shell.


Overview

A typical interactive usage is typing the command bc on a
Unix Unix (; trademarked as UNIX) is a family of multitasking, multiuser computer operating systems that derive from the original AT&T Unix, whose development started in 1969 at the Bell Labs research center by Ken Thompson, Dennis Ritchie, ...
command prompt Command Prompt, also known as cmd.exe or cmd, is the default command-line interpreter for the OS/2, eComStation, ArcaOS, Microsoft Windows (Windows NT family and Windows CE family), and ReactOS operating systems. On Windows CE .NET 4.2, ...
and entering a mathematical expression, such as , whereupon will be output. While bc can work with arbitrary precision, it actually defaults to zero digits after the decimal point, so the expression yields (results are truncated, not rounded). This can surprise new bc users unaware of this fact. The option to bc sets the default ''scale'' (digits after the decimal point) to 20 and adds several additional mathematical functions to the language.


History

bc first appeared in
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 ...
in 1975. It was written by
Lorinda Cherry Lorinda Cherry ( Landgraf; November 18, 1944 – February 2022) was an American computer scientist and programmer. Much of her career was spent at Bell Labs, where she was for many years a member of the original Unix Lab. Cherry developed severa ...
of
Bell Labs Nokia Bell Labs, originally named Bell Telephone Laboratories (1925–1984), then AT&T Bell Laboratories (1984–1996) and Bell Labs Innovations (1996–2007), is an American industrial research and scientific development company owned by mul ...
as a front end to dc, an arbitrary-precision calculator written by Robert Morris and Cherry. dc performed arbitrary-precision computations specified in
reverse Polish notation Reverse Polish notation (RPN), also known as reverse Łukasiewicz notation, Polish postfix notation or simply postfix notation, is a mathematical notation in which operators ''follow'' their operands, in contrast to Polish notation (PN), in wh ...
. bc provided a conventional programming-language interface to the same capability via a simple
compiler In computing, a compiler is a computer program that translates computer code written in one programming language (the ''source'' language) into another language (the ''target'' language). The name "compiler" is primarily used for programs tha ...
(a single
yacc Yacc (Yet Another Compiler-Compiler) is a computer program for the Unix operating system developed by Stephen C. Johnson. It is a Look Ahead Left-to-Right Rightmost Derivation (LALR) parser generator, generating a LALR parser (the part of a co ...
source file comprising a few hundred lines of code), which converted a C-like syntax into dc notation and
piped A pipe is a tubular section or hollow cylinder, usually but not necessarily of circular cross-section, used mainly to convey substances which can flow — liquids and gases ( fluids), slurries, powders and masses of small solids. ...
the results through dc. In 1991,
POSIX The Portable Operating System Interface (POSIX) is a family of standards specified by the IEEE Computer Society for maintaining compatibility between operating systems. POSIX defines both the system- and user-level application programming in ...
rigorously defined and standardized bc. Three 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 systems. The second is the
free software Free software or libre software is computer software distributed under terms that allow users to run the software for any purpose as well as to study, change, and distribute it and any adapted versions. Free software is a matter of liberty, n ...
GNU GNU () is an extensive collection of free software (383 packages as of January 2022), which can be used as an operating system or can be used in parts with other operating systems. The use of the completed GNU tools led to the family of operat ...
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). The third is a re-implementation by OpenBSD in 2003.


Implementations


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,
array An array is a systematic arrangement of similar objects, usually in rows and columns. Things called an array include: {{TOC right Music * In twelve-tone and serial composition, the presentation of simultaneous twelve-tone sets such that the ...
and
function Function or functionality may refer to: Computing * Function key, a type of key on computer keyboards * Function model, a structured representation of processes in a system * Function object or functor or functionoid, a concept of object-oriente ...
names and most standard arithmetic operators, as well as the familiar
control-flow In computer science, control flow (or flow of control) is the order in which individual statements, instructions or function calls of an imperative program are executed or evaluated. The emphasis on explicit control flow distinguishes an ''imp ...
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 In computer science, arbitrary-precision arithmetic, also called bignum arithmetic, multiple-precision arithmetic, or sometimes infinite-precision arithmetic, indicates that calculations are performed on numbers whose digits of precision are li ...
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.


Mathematical operators


=Exactly as C

= The following POSIX bc
operators Operator may refer to: Mathematics * A symbol indicating a mathematical operation * Logical operator or logical connective in mathematical logic * Operator (mathematics), mapping that acts on elements of a space to produce elements of another sp ...
behave exactly like their C counterparts: + - * / += -= *= /= ++ -- < >

!= <= >=
( )


=Similar to C

= The modulus operators, % and %= behave exactly like their C counterparts only when the global scale variable is set to 0, i.e. all calculations are integer-only. Otherwise the computation is done with the appropriate scale. a%b is defined as a-(a/b)*b. Examples: $ bc bc 1.06 Copyright 1991-1994, 1997, 1998, 2000 Free Software Foundation, Inc. This is free software with ABSOLUTELY NO WARRANTY. For details type `warranty'. scale=0; 5%3 2 scale=1; 5%3 .2 scale=20; 5%3 .00000000000000000002


=Conflicting with C

= The operators ^ ^= superficially resemble the C bitwise
exclusive-or Exclusive or or exclusive disjunction is a logical operation that is true if and only if its arguments differ (one is true, the other is false). It is symbolized by the prefix operator J and by the infix operators XOR ( or ), EOR, EXOR, , , ...
operators, but are in fact the bc integer exponentiation operators. Of particular note, the use of the ^ operator with negative numbers does not follow the C operator precedence. -2^2 gives the answer of 4 under bc rather than −4.


="Missing" operators relative to C

= The
bitwise In computer programming, a bitwise operation operates on a bit string, a bit array or a binary numeral (considered as a bit string) at the level of its individual bits. It is a fast and simple action, basic to the higher-level arithmetic operat ...
, boolean and
conditional Conditional (if then) may refer to: *Causal conditional, if X then Y, where X is a cause of Y *Conditional probability, the probability of an event A given that another event B has occurred *Conditional proof, in logic: a proof that asserts a co ...
operators: & , ^ && , , &= , = ^= &&= , , = << >> <<= >>= ?: are not available in POSIX bc.


Built-in functions

The sqrt() function for calculating
square root In mathematics, a square root of a number is a number such that ; in other words, a number whose '' square'' (the result of multiplying the number by itself, or  ⋅ ) is . For example, 4 and −4 are square roots of 16, because . ...
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 In mathematics, sine and cosine are trigonometric functions of an angle. The sine and cosine of an acute angle are defined in the context of a right triangle: for the specified angle, its sine is the ratio of the length of the side that is opp ...
, cosine,
arctangent In mathematics, the inverse trigonometric functions (occasionally also called arcus functions, antitrigonometric functions or cyclometric functions) are the inverse functions of the trigonometric functions (with suitably restricted domains). Spe ...
,
natural logarithm The natural logarithm of a number is its logarithm to the base of the mathematical constant , which is an irrational and transcendental number approximately equal to . The natural logarithm of is generally written as , , or sometimes, if ...
, the
exponential function The exponential function is a mathematical function denoted by f(x)=\exp(x) or e^x (where the argument is written as an exponent). Unless otherwise specified, the term generally refers to the positive-valued function of a real variable, ...
and the two parameter
Bessel function Bessel functions, first defined by the mathematician Daniel Bernoulli and then generalized by Friedrich Bessel, are canonical solutions of Bessel's differential equation x^2 \frac + x \frac + \left(x^2 - \alpha^2 \right)y = 0 for an arbitrar ...
''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, so things such as modulo may work unexpectedly. For example, writing bc -l and then the command print 3%2 outputs 0. But writing scale=0 after bc -l and then the command print 3%2 will output 1.


Plan 9 bc

Plan 9 bc is identical to 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 operator In logic, a logical connective (also called a logical operator, sentential connective, or sentential operator) is a logical constant. They can be used to connect logical formulas. For instance in the syntax of propositional logic, the binary ...
s are additional to those in POSIX bc: && , , ! They 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) /* Use the fact that x^y

e^(y*log(x)) */ define p(x,y)


Calculating π to 10000 digits

Calculate pi using the builtin
arctangent In mathematics, the inverse trigonometric functions (occasionally also called arcus functions, antitrigonometric functions or cyclometric functions) are the inverse functions of the trigonometric functions (with suitably restricted domains). Spe ...
function, : $ bc -lq scale=10000 4*a(1) # The atan of 1 is 45 degrees, which is pi/4 in radians. # This may take several minutes to calculate.


A translated C function

Because the syntax of bc is similar to that of C, published numerical functions 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 The ''Journal of Statistical Software'' is a peer-reviewed open-access scientific journal that publishes papers related to statistical software. The ''Journal of Statistical Software'' was founded in 1996 by Jan de Leeuw of the Department of Sta ...
(July 2004, Volume 11, Issue 5),
George Marsaglia George Marsaglia (March 12, 1924 – February 15, 2011) was an American mathematician and computer scientist. He is best known for creating the diehard tests, a suite of software for measuring statistical randomness. Research on random numbers ...
published the following C code for the cumulative normal distribution: double Phi(double x) With some necessary changes to accommodate bc's different syntax, and realizing that the constant "0.9189..." is actually log(2*PI)/2, this can be translated to the following GNU bc code: define phi(x)


Using bc in shell scripts

bc can be used non-interactively, with input through a
pipe Pipe(s), PIPE(S) or piping may refer to: Objects * Pipe (fluid conveyance), a hollow cylinder following certain dimension rules ** Piping, the use of pipes in industry * Smoking pipe ** Tobacco pipe * Half-pipe and quarter pipe, semi-circular ...
. This is useful inside
shell script A shell script is a computer program designed to be run by a Unix shell, a command-line interpreter. The various dialects of shell scripts are considered to be scripting languages. Typical operations performed by shell scripts include file man ...
s. For example: $ result=$(echo "scale=2; 5 * 7 /3;" , bc) $ echo $result 11.66 In contrast, note that the
bash shell Bash is a Unix shell and command language written by Brian Fox for the GNU Project as a free software replacement for the Bourne shell. First released in 1989, it has been used as the default login shell for most Linux distributions. Bash was o ...
only performs integer arithmetic, e.g.: $ result=$((5 * 7 /3)) $ echo $result 11 One can also use the here-string idiom (in bash, ksh, csh): $ bc -l <<< "5*7/3" 11.66666666666666666666


See also

*
dc programming language dc (''desk calculator'') is a cross-platform reverse-Polish calculator which supports arbitrary-precision arithmetic. Written by Lorinda Cherry and Robert Morris at Bell Labs, it is one of the oldest Unix utilities, preceding even the invention ...
*
C programming language ''The C Programming Language'' (sometimes termed ''K&R'', after its authors' initials) is a computer programming book written by Brian Kernighan and Dennis Ritchie, the latter of whom originally designed and implemented the language, as well a ...
* hoc programming language


References

*
GNU bc manual page


*
7th Edition Unix bc manual page

A comp.compilers article on the design and implementation of C-bc

6th Edition Unix bc source code
the first release of bc, from May 1975, compiling bc syntax into dc syntax
GNU bc source code


External links


Dittmer, I. 1993. Error in Unix commands dc and bc for multiple-precision-arithmetic. SIGNUM Newsl. 28, 2 (Apr. 1993), 8–11.

Collection of useful GNU bc functions

GNU bc
(and a
alpha version
from the Free Software Foundation

from
GnuWin32 The G''nu''W''in''32 project provides native ports in the form of executable computer programs, patches, and source code for various GNU and open source tools and software, much of it modified to run on the 32-bit Windows platform. The ports inc ...

Gavin Howard bc
- another open source implementation of bc by Gavin Howard with GNU and BSD extensions
X-bc
- A Graphical User Interface to bc *

- contains functions of trigonometry, exponential functions, functions of number theory and some mathematical constants *

- contains particle masses, basic constants, such as speed of light in the vacuum and the gravitational constant {{Plan 9 commands Software calculators Cross-platform free software Free mathematics software Numerical programming languages Standard Unix programs Unix SUS2008 utilities Plan 9 commands