Bc programming language

Bc programming language

bc is "an arbitrary precision calculator language" with syntax similar to the C programming language. It is generally used by typing the command bc on a Unix command prompt and entering a mathematical expression, such as "(1 + 3) * 2", whereupon "8" will be output.

There are currently two main dialects: the rigorously defined POSIX bc, and its direct descendant, the much expanded GNU bc (also, GNU bc is available for a wider range of platforms, such as Microsoft Windows). A more recent dialect, Plan 9 bc, is a superset of the former and subset of the latter.

All three forms of bc can be executed as either a mathematical scripting language or as an interactive mathematical shell.

POSIX bc

The POSIX standardised 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 fixed precision floating-point 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:

% %=

... 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, 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.

Standard library functions

bc's standard library 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.

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))

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

A translated C function

Because the syntax of bc is very similar to that of C, 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 (July 2004, Volume 11, Issue 5), George Marsaglia 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. This is useful inside shell scripts. 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

* C programming language
* dc programming language
* hoc programming language

References

*man|cu|bc|SUS|arbitrary-precision arithmetic language
* [http://www.gnu.org/software/bc/manual/html_mono/bc.html GNU bc manual page]
* [http://plan9.bell-labs.com/magic/man2html/1/bc Plan 9 bc manual page]
* [http://plan9.bell-labs.com/7thEdMan/vol2/bc 7th Edition Unix bc manual page]
* [http://compilers.iecc.com/comparch/article/95-09-015 A comp.compilers article on the design and implementation of C-BC]

External links

* [http://doi.acm.org/10.1145/152923.152925 Dittmer, I. 1993. Error in Unix commands dc and bc for multiple-precision-arithmetic. SIGNUM Newsl. 28, 2 (Apr. 1993), 8&ndash;11.]
* [http://sciencesoft.at/index.jsp?link=bc&lang=en Online version of GNU bc]
* [http://www.cyreksoft.yorks.com/gnu-bc/ Collection of useful GNU bc functions]
* [http://www.pixelbeat.org/scripts/bc Collection of useful GNU bc integer functions]
* [http://directory.fsf.org/gnu/bc.html GNU bc] (and an [http://alpha.gnu.org/gnu/bc/ alpha version] ) from the Free Software Foundation
* [http://gnuwin32.sourceforge.net/packages/bc.htm Bc for Windows] from GnuWin32
* [http://x-bc.sourceforge.net/ X-Bc] - A Graphical User Interface to Bc
** [http://x-bc.sourceforge.net/extensions_bc.html extensions.bc] - contains functions of trigonometry, exponential functions, functions of number theory and some mathematical constants
** [http://x-bc.sourceforge.net/scientific_constants_bc.html scientific_constants.bc] - contains particle masses, basic constants, such as speed of light in the vacuum and the gravitational constant


Wikimedia Foundation. 2010.

Игры ⚽ Поможем написать реферат

Look at other dictionaries:

  • Programming language — lists Alphabetical Categorical Chronological Generational A programming language is an artificial language designed to communicate instructions to a machine, particularly a computer. Programming languages can be used to create programs that… …   Wikipedia

  • Programming language theory — (commonly known as PLT) is a branch of computer science that deals with the design, implementation, analysis, characterization, and classification of programming languages and programming language features. It is a multi disciplinary field, both… …   Wikipedia

  • Programming Language Design and Implementation — (PLDI) is one of the ACM SIGPLAN s most important conferences. The precursor of PLDI was the Symposium on Compiler Optimization, held July 27–28, 1970 at the University of Illinois at Urbana Champaign and chaired by Robert S. Northcote. That… …   Wikipedia

  • Programming Language for Business — or PL/B is a business oriented programming language originally called DATABUS and designed by Datapoint in the early 1970s as an alternative to COBOL because its 8 bit computers could not fit COBOL into their limited memory, and because COBOL did …   Wikipedia

  • programming language — ➔ language * * * programming language UK US noun [C] ► COMPUTER LANGUAGE(Cf. ↑computer language) …   Financial and business terms

  • programming language — Language Lan guage, n. [OE. langage, F. langage, fr. L. lingua the tongue, hence speech, language; akin to E. tongue. See {Tongue}, cf. {Lingual}.] [1913 Webster] 1. Any means of conveying or communicating ideas; specifically, human speech; the… …   The Collaborative International Dictionary of English

  • Programming Language One — Programming Language One, oft als PL/I (auch PL/1, PL1 oder PLI) abgekürzt ist eine Programmiersprache, die in den 1960er Jahren von IBM entwickelt wurde. Die Bezeichnung PL/1 ist vor allem in Deutschland gebräuchlich. Ursprünglich wurde PL/I… …   Deutsch Wikipedia

  • Programming Language 1 — noun A computer programming language which combines the best qualities of commercial and scientific oriented languages (abbrev PL/1) • • • Main Entry: ↑programme …   Useful english dictionary

  • Programming Language —   [engl.], Programmiersprache …   Universal-Lexikon

  • Programming language specification — A programming language specification is an artifact that defines a programming language so that users and implementors can agree on what programs in that language mean.A programming language specification can take several forms, including the… …   Wikipedia

  • programming language — noun (computer science) a language designed for programming computers • Syn: ↑programing language • Topics: ↑computer science, ↑computing • Hypernyms: ↑artificial language …   Useful english dictionary

Share the article and excerpts

Direct link
Do a right-click on the link above
and select “Copy Link”