Bc (programming language)

Last updated
bc
Developer(s) Robert Morris and Lorinda Cherry of Bell Labs
Initial release1975, 4849 years ago
Operating system Unix, Unix-like, Plan 9, FreeDOS
Platform Cross-platform
Type Command

bc, for basic calculator, is "an arbitrary-precision calculator language" with syntax similar to the C programming language. bc is typically used as either a mathematical scripting language or as an interactive mathematical shell.

Contents

Overview

A typical interactive usage is typing the command bc on a Unix 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 (results are truncated, not rounded). 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.

History

bc first appeared in Version 6 Unix in 1975. It was written by Lorinda Cherry of Bell Labs 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. bc provided a conventional programming-language interface to the same capability via a simple compiler (a single yacc source file comprising a few hundred lines of code), which converted a C-like syntax into dc notation and piped the results through dc.

In 1991, POSIX 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 GNU 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 and function names and most standard arithmetic operators, as well as the familiar control-flow 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.

Mathematical operators

Exactly as C

The following POSIX bc operators 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.06Copyright 1991-1994, 1997, 1998, 2000 Free Software Foundation, Inc.This is free software with ABSOLUTELY NO WARRANTY.For details type `warranty'.scale=0; 5%32scale=1; 5%3.2scale=20; 5%3.00000000000000000002
Conflicting with C

The operators

^     ^=

superficially resemble the C bitwise exclusive-or 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, boolean and conditional operators:

&     |     ^     &&    || &=    |=    ^=    &&=   ||= <<    >> <<=   >>= ?:

are not available in POSIX bc.

Built-in functions

The sqrt() function for calculating square roots 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, cosine, arctangent, natural logarithm, the exponential function and the two parameter Bessel function 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 bc standard library [1]
bc commandFunctionDescription
s(x) Sine Takes x, an angle in radians
c(x) Cosine Takes x, an angle in radians
a(x) Arctangent Returns radians
l(x) Natural logarithm
e(x) Exponential function
j(n,x) Bessel function Returns the order-n Bessel function of x.

The -l option changes the scale to 20, [1] 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 operators 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){auto s     s =scalescale=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)))}

Calculating π to 10000 digits

Calculate pi using the builtin arctangent function, a():

$ bc-lq scale=100004*a(1) # The atan of 1 is 45 degrees, which is pi/4 in radians.       # Thismaytakeseveralminutestocalculate. 

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 (July 2004, Volume 11, Issue 5), George Marsaglia published the following C code for the cumulative normal distribution:

doublePhi(doublex){longdoubles=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 some necessary changes to accommodate bc's different syntax, and noting that the constant "0.9189..." is actually log(2*PI)/2, this can be translated to the following GNU bc code:

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

Using bc in shell scripts

bc can be used non-interactively, with input through a pipe. This is useful inside shell scripts. For example:

$ result=$(echo"scale=2; 5 * 7 /3;"|bc)$ echo$result11.66

In contrast, note that the bash shell only performs integer arithmetic, e.g.:

$ result=$((5*7/3))$ echo$result11

One can also use the here-string idiom (in bash, ksh, csh):

$ bc-l<<<"5*7/3"11.66666666666666666666

See also

Related Research Articles

<span class="mw-page-title-main">AWK</span> Programming language

AWK is a domain-specific language designed for text processing and typically used as a data extraction and reporting tool. Like sed and grep, it is a filter, and is a standard feature of most Unix-like operating systems.

<span class="mw-page-title-main">Bash (Unix shell)</span> GNU replacement for the Bourne 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. The shell's name is an acronym for Bourne-Again SHell, a pun on the name of the Bourne shell that it replaces and the notion of being "born again". First released in 1989, it has been used as the default login shell for most Linux distributions and it was one of the first programs Linus Torvalds ported to Linux, alongside GCC. It is available on nearly all modern operating systems.

C is a general-purpose computer programming language. It was created in the 1970s by Dennis Ritchie, and remains very widely used and influential. By design, C's features cleanly reflect the capabilities of the targeted CPUs. It has found lasting use in operating systems, device drivers, and protocol stacks, but its use in application software has been decreasing. C is commonly used on computer architectures that range from the largest supercomputers to the smallest microcontrollers and embedded systems.

<span class="mw-page-title-main">Scheme (programming language)</span> Dialect of Lisp

Scheme is a dialect of the Lisp family of programming languages. Scheme was created during the 1970s at the MIT Computer Science and Artificial Intelligence Laboratory and released by its developers, Guy L. Steele and Gerald Jay Sussman, via a series of memos now known as the Lambda Papers. It was the first dialect of Lisp to choose lexical scope and the first to require implementations to perform tail-call optimization, giving stronger support for functional programming and associated techniques such as recursive algorithms. It was also one of the first programming languages to support first-class continuations. It had a significant influence on the effort that led to the development of Common Lisp.

<span class="mw-page-title-main">Rounding</span> Replacing a number with a simpler value

Rounding means replacing a number with an approximate value that has a shorter, simpler, or more explicit representation. For example, replacing $23.4476 with $23.45, the fraction 312/937 with 1/3, or the expression √2 with 1.414.

<span class="mw-page-title-main">Conditional (computer programming)</span> Control flow statement that executes code according to some condition(s)

In computer science, conditionals are programming language commands for handling decisions. Specifically, conditionals perform different computations or actions depending on whether a programmer-defined Boolean condition evaluates to true or false. In terms of control flow, the decision is always achieved by selectively altering the control flow based on some condition . Although dynamic dispatch is not usually classified as a conditional construct, it is another way to select between alternatives at runtime. Conditional statements are the checkpoints in the programe that determines behaviour according to situation.

The printf family of functions in the C programming language are a set of functions that take a format string as input among a variable sized list of other values and produce as output a string that corresponds to the format specifier and given input values. The string is written in a simple template language: characters are usually copied literally into the function's output, but format specifiers, which start with a % character, indicate the location and method to translate a piece of data to characters. The design has been copied to expose similar functionality in other programming languages.

dd is a command-line utility for Unix, Plan 9, Inferno, and Unix-like operating systems and beyond, the primary purpose of which is to convert and copy files. On Unix, device drivers for hardware and special device files appear in the file system just like normal files; dd can also read and/or write from/to these files, provided that function is implemented in their respective driver. As a result, dd can be used for tasks such as backing up the boot sector of a hard drive, and obtaining a fixed amount of random data. The dd program can also perform conversions on the data as it is copied, including byte order swapping and conversion to and from the ASCII and EBCDIC text encodings.

dc is a cross-platform reverse-Polish calculator which supports arbitrary-precision arithmetic. It was written by Lorinda Cherry and Robert Morris at Bell Labs. It is one of the oldest Unix utilities, preceding even the invention of the C programming language. Like other utilities of that vintage, it has a powerful set of features but terse syntax. Traditionally, the bc calculator program was implemented on top of dc.

m4 is a general-purpose macro processor included in most Unix-like operating systems, and is a component of the POSIX standard.

<span class="mw-page-title-main">Unix time</span> Date and time representation system widely used in computing

Unix time is a date and time representation widely used in computing. It measures time by the number of non-leap seconds that have elapsed since 00:00:00 UTC on 1 January 1970, the Unix epoch. In modern computing, values are sometimes stored with higher granularity, such as microseconds or nanoseconds.

<span class="mw-page-title-main">C data types</span> Data types supported by the C programming language

In the C programming language, data types constitute the semantics and characteristics of storage of data elements. They are expressed in the language syntax in form of declarations for memory locations or variables. Data types also determine the types of operations or methods of processing of data elements.

<span class="mw-page-title-main">Mathomatic</span> Computer algebra system

Mathomatic is a free, portable, general-purpose computer algebra system (CAS) that can symbolically solve, simplify, combine and compare algebraic equations, and can perform complex number, modular, and polynomial arithmetic, along with standard arithmetic. It does some symbolic calculus (derivative, extrema, Taylor series, and polynomial integration and Laplace transforms), numerical integration, and handles all elementary algebra except logarithms. Trigonometric functions can be entered and manipulated using complex exponentials, with the GNU m4 preprocessor. Not currently implemented are general functions like f(x), arbitrary-precision and interval arithmetic, and matrices.

expr is a command line utility on Unix and Unix-like operating systems which evaluates an expression and outputs the corresponding value. It first appeared in Unix v7. The command is available for Microsoft Windows as part of the UnxUtils collection of native Win32 ports of common GNU Unix-like utilities. The expr command has also been ported to the IBM i operating system.

This article compares a large number of programming languages by tabulating their data types, their expression, statement, and declaration syntax, and some common operating-system interfaces.

Class Library for Numbers (CLN) is a free library for arbitrary precision arithmetic. It operates on signed integers, rational numbers, floating point numbers, complex numbers, modular numbers, and univariate polynomials. Its implementation programming language is C++.

Some programming languages provide a complex data type for complex number storage and arithmetic as a built-in (primitive) data type.

Some programming languages provide a built-in (primitive) rational data type to represent rational numbers like 1/3 and -11/17 without rounding, and to do arithmetic on them. Examples are the ratio type of Common Lisp, and analogous types provided by most languages for algebraic computation, such as Mathematica and Maple. Many languages that do not have a built-in rational type still provide it as a library-defined type.

Getopt is a C library function used to parse command-line options of the Unix/POSIX style. It is a part of the POSIX specification, and is universal to Unix-like systems. It is also the name of a Unix program for parsing command line arguments in shell scripts.

References

  1. 1 2 bc : arbitrary-precision arithmetic language  Shell and Utilities Reference, The Single UNIX Specification , Version 4 from The Open Group