![]() | This article includes a list ofgeneral references, butit lacks sufficient correspondinginline citations. Please help toimprove this article byintroducing more precise citations.(June 2013) (Learn how and when to remove this message) |
bc | |
---|---|
Developer(s) | Robert Morris andLorinda Cherry ofBell Labs |
Initial release | 1975, 49–50 years ago |
Operating system | Unix,Unix-like,Plan 9,FreeDOS |
Platform | Cross-platform |
Type | Command |
bc forbasic calculator, is "anarbitrary-precision calculator language" with syntax similar to theC programming language. bc is typically used as either a mathematical scripting language or as an interactive mathematical shell.
A typical interactive usage is typing the commandbc
on aUnixcommand prompt and entering a mathematical expression, such as(1 + 3) * 2
, whereupon8 will be output. While bc can work with arbitrary precision, it actually defaults to zero digits after the decimal point, so the expression2/3
yields0 (results are truncated, not rounded). This can surprise new bc users unaware of this fact. The-l
option to bc sets the defaultscale (digits after the decimal point) to 20 and adds several additional mathematical functions to the language.
bc first appeared inVersion 6 Unix in 1975. It was written byLorinda Cherry ofBell Labs as a front end todc, an arbitrary-precision calculator written byRobert Morris and Cherry. dc performed arbitrary-precision computations specified inreverse Polish notation. bc provided a conventional programming-language interface to the same capability via a simplecompiler (a singleyacc source file comprising a few hundred lines of code), which converted aC-like syntax into dc notation andpiped the results through dc.
In 1991,POSIX rigorously defined and standardized bc. Four implementations of this standard survive today: The first is the traditional Unix implementation, a front-end to dc, which survives in Unix andPlan 9 systems. The second is thefree softwareGNU 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 abytecode interpreter). The third is a re-implementation byOpenBSD in 2003. The fourth is an independent implementation by Gavin Howard[1] that is included inAndroid (operating system),[2][3]FreeBSD as of 13.3-RELEASE,[4][5][6] andmacOS as of 13.0.[7][8][9]
The POSIX standardized bc language is traditionally written as a program in thedc 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-lettervariable,array andfunction names and most standard arithmetic operators, as well as the familiarcontrol-flow constructs (if(cond)...
,while(cond)...
andfor(init;cond;inc)...
) from C. Unlike C, anif
clause may not be followed by anelse
.
Functions are defined using adefine
keyword, and values are returned from them using areturn
followed by the return value in parentheses. Theauto
keyword (optional in C) is used to declare a variable as local to a function.
All numbers and variable contents arearbitrary-precision numbers whose precision (in decimal places) is determined by the globalscale
variable.
Thenumeric base of input (in interactive mode), output and program constants may be specified by setting the reservedibase
(input base) andobase
(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.
The following POSIX bcoperators behave exactly like their C counterparts:
+ - * /+= -= *= /=++ -- < >== != <= >=( ) [ ] { }
Themodulus operators,%
and%=
behave exactly like their C counterparts only when the globalscale
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 asa-(a/b)*b
. Examples:
$bcbc 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
The operators
^ ^=
superficially resemble the C bitwiseexclusive-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.
Thebitwise,Boolean andconditional operators:
& | ^ && ||&= |= ^= &&= ||=<< >><<= >>=?:
are not available in POSIX bc.
Thesqrt()
function for calculatingsquare roots is POSIX bc's only built-in mathematical function. Other functions are available in an external standard library.
Thescale()
function for determining the precision (as with thescale
variable) of its argument and thelength()
function for determining the number of significant decimal digits in its argument are also built-in.
bc's standard math library (defined with the-l option) contains functions for calculatingsine,cosine,arctangent,natural logarithm, theexponential function and the two parameterBessel functionJ. Most standard mathematical functions (including the other inverse trigonometric functions) can be constructed using these. See external links for implementations of many other functions.
bc command | Function | Description |
---|---|---|
s(x) | Sine | Takesx, an angle inradians |
c(x) | Cosine | Takesx, 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 ofx. |
The-l option changes the scale to 20,[10] so things such as modulo may work unexpectedly. For example, writingbc -l
and then the commandprint 3%2
outputs 0. But writingscale=0
afterbc -l
and then the commandprint 3%2
will output 1.
Plan 9 bc is identical to POSIX bc but for an additionalprint
statement.
GNU bc derives from the POSIX standard and includes many extensions. 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, anif
clause may be followed by anelse
.
Output is achieved either by deliberately not assigning a result of a calculation to a variable (the POSIX way) or by using the addedprint
statement.
Furthermore, aread
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-inlast
variable.
The followinglogical operators are additional to those in POSIX bc:
&& || !
They are available for use in conditional statements (such as within anif
statement). Note, however, that there are still no equivalent bitwise or assignment operations.
All functions available in GNU bc are inherited from POSIX. No further functions are provided as standard with the GNU distribution.
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 function to return the integer part of x */define i(x){auto s s=scalescale=0 x/=1/* round x down */scale= sreturn(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)))}
Calculatepi using the builtinarctangent function,a():
$bc-lqscale=100004*a(1) # The atan of 1 is 45 degrees, which is pi/4 in radians. #Thismaytakeseveralminutestocalculate.
Because the syntax of bc is similar to that ofC, 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 theJournal of Statistical Software (July 2004, Volume 11, Issue 5),George Marsaglia published the following C code for thecumulative 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)}
bc can be used non-interactively, with input through apipe. This is useful insideshell scripts. For example:
$result=$(echo"scale=2; 5 * 7 /3;"|bc)$echo$result11.66
In contrast, note that thebash shell only performs integer arithmetic, e.g.:
$result=$((5*7/3))$echo$result11
One can also use thehere-string idiom (in bash, ksh, csh):
$bc-l<<<"5*7/3"11.66666666666666666666
bc
: arbitrary-precision arithmetic language – Shell and Utilities Reference,The Single UNIX Specification, Version 5 fromThe Open Groupbc
: arbitrary-precision arithmetic language – Shell and Utilities Reference,The Single UNIX Specification, Version 5 fromThe Open Groupbc(1)
– Plan 9 Programmer's Manual, Volume 1