Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
Bc (programming language)
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
{{Short description|UNIX utility which implements an arbitrary-precision arithmetic language}}{{Not to be confused with|B programming language|C programming language}}{{more footnotes|date=June 2013}} {{lowercase|title=bc programming language}} {{Infobox software | name = bc | logo = | screenshot = | screenshot size = | caption = | developer = [[Robert Morris (cryptographer)|Robert Morris]] and [[Lorinda Cherry]] of [[Bell Labs]] | released = {{Release year|df=yes|1975}} | latest release version = | latest release date = | operating system = [[Unix]], [[Unix-like]], [[Plan 9 from Bell Labs|Plan 9]], [[FreeDOS]] | platform = [[Cross-platform]] | genre = [[Command (computing)|Command]] | license = | website = }} '''bc''' for ''basic calculator'', is "an [[Arbitrary-precision arithmetic|arbitrary-precision]] calculator language" with syntax similar to the [[C (programming language)|C programming language]]. 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 <code>bc</code> on a [[Unix]] [[Command-line interface#Command prompt|command prompt]] and entering a mathematical expression, such as {{code|(1 + 3) * 2}}, whereupon {{samp|8}} will be output. While bc can work with arbitrary precision, it actually defaults to zero digits after the decimal point, so the expression {{code|2/3}} yields {{samp|0}} (results are truncated, not rounded). This can surprise new bc users unaware of this fact. The {{code|-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 (computer program)|dc]], an arbitrary-precision calculator written by [[Robert Morris (cryptographer)|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 (programming language)|C]]-like syntax into dc notation and [[Pipeline (Unix)|piped]] 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 and [[Plan 9 from Bell Labs|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. The fourth is an independent implementation by Gavin Howard<ref name=":1">[https://git.gavinhoward.com/gavin/bc An implementation of Unix dc and POSIX bc with GNU and BSD extensions]</ref> that is included in [[Android (operating system)]],<ref name=":2">{{Cite web|url=https://android.googlesource.com/platform/system/core/+/master/shell_and_utilities/README.md|title=Android's shell and utilities|website=android.googlesource.com}}</ref><ref name=":3">{{cite web | url=https://android.googlesource.com/platform/external/bc/ | title=Platform/External/Bc - Git at Google }}</ref> [[FreeBSD]] as of 13.3-RELEASE,<ref name=":4">{{Cite web|url=https://forums.freebsd.org/threads/freebsd-13-3-whats-new-and-how-did-we-get-here.92596/|title=FreeBSD 13.3: What's new, and how did we get here?|date=March 5, 2024|website=The FreeBSD Forums}}</ref><ref name=":5">{{Cite web|url=https://man.freebsd.org/cgi/man.cgi?query=bc&apropos=0&sektion=1&manpath=FreeBSD+14.1-RELEASE&arch=default&format=html|title=bc(1)|website=man.freebsd.org}}</ref><ref name=":6">{{Cite web|url=https://cgit.freebsd.org/src/tree/contrib/bc|title=bc Β« contrib - src - FreeBSD source tree|website=cgit.freebsd.org}}</ref> and [[macOS]] as of 13.0.<ref name=":7">{{Cite web|url=https://opensource.apple.com/releases/|title=Apple Open Source|website=opensource.apple.com}}</ref><ref name=":8">{{Cite web|url=https://github.com/apple-oss-distributions/bc/tree/main/bc|title=bc/bc at main Β· apple-oss-distributions/bc|website=GitHub}}</ref><ref name=":9">{{cite web | url=https://gavinhoward.com/2023/02/my-code-conquered-another-os/ | title=My Code Conquered Another OS! | Gavin D. Howard }}</ref> ==Implementations== ===POSIX bc=== The POSIX standardized bc language is traditionally written as a program in the [[dc (computer program)|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 (programming)|variable]], [[array data structure|array]] and [[function (programming)|function]] names and most standard arithmetic operators, as well as the familiar [[control-flow]] constructs (<code>'''if('''cond''')'''...</code>, <code>'''while('''cond''')'''...</code> and <code>'''for('''init''';'''cond''';'''inc''')'''...</code>) from C. Unlike C, an '''<code>if</code>''' clause may not be followed by an '''<code>else</code>'''. Functions are defined using a '''<code>define</code>''' keyword, and values are returned from them using a '''<code>return</code>''' followed by the return value in parentheses. The '''<code>auto</code>''' 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 '''<code>scale</code>''' variable. The [[radix|numeric base]] of input (in interactive mode), output and program constants may be specified by setting the reserved '''<code>ibase</code>''' (input base) and '''<code>obase</code>''' (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 '''<code>/*</code>''' and '''<code>*/</code>''' (start and end comment) symbols. ====Mathematical operators==== =====Exactly as C===== The following POSIX bc [[Operator (programming)|operators]] behave exactly like their C counterparts: + - * / += -= *= /= ++ -- < > <nowiki>== != <= >=</nowiki> ( ) [ ] { } =====Similar to C===== The [[Modulus operator|modulus]] operators, <code>%</code> and <code>%=</code> behave exactly like their C counterparts only when the global '''<code>scale</code>''' variable is set to 0, i.e. all calculations are integer-only. Otherwise the computation is done with the appropriate scale. <code>a%b</code> is defined as <code>a-(a/b)*b</code>. Examples: <syntaxhighlight lang="console" highlight="6,8,10"> $ 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 </syntaxhighlight> =====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 <code>^</code> operator with negative numbers does not follow the C operator precedence. <code>-2^2</code> gives the answer of 4 under bc rather than β4. ====="Missing" operators relative to C===== The [[bitwise operation|bitwise]], [[Boolean logic|Boolean]] and [[conditional (programming)|conditional]] operators: & | ^ && || &= |= ^= &&= ||= << >> <<= >>= ?: are not available in POSIX bc. ====Built-in functions==== The '''<code>sqrt()</code>''' function for calculating [[square root]]s is POSIX bc's only built-in mathematical function. Other functions are available in an external standard library. The '''<code>scale()</code>''' function for determining the precision (as with the '''<code>scale</code>''' variable) of its argument and the '''<code>length()</code>''' 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. {| class="wikitable" |+The bc standard library<ref name=":0">{{man|cu|bc|SUS|arbitrary-precision arithmetic language}}</ref> !bc command !Function !Description |- |<code>s(x)</code> |[[Sine]] |Takes ''x'', an angle in [[radian]]s |- |<code>c(x)</code> |[[Cosine]] |Takes ''x'', an angle in radians |- |<code>a(x)</code> |[[Arctangent]] |Returns radians |- |<code>l(x)</code> |[[Natural logarithm]] | |- |<code>e(x)</code> |[[Exponential function]] | |- |<code>j(n,x)</code> |[[Bessel function]] |Returns the order-''n'' Bessel function of ''x''. |} The '''-l''' option changes the scale to 20,<ref name=":0" /> so things such as modulo may work unexpectedly. For example, writing <code>bc -l</code> and then the command <code>print 3%2</code> outputs 0. But writing <code>scale=0</code> after <code>bc -l</code> and then the command <code>print 3%2</code> will output 1. ===Plan 9 bc=== [[Plan 9 from Bell Labs|Plan 9]] bc is identical to POSIX bc but for an additional '''<code>print</code>''' statement. ===GNU bc=== 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, an '''<code>if</code>''' clause may be followed by an '''<code>else</code>'''. Output is achieved either by deliberately not assigning a result of a calculation to a variable (the POSIX way) or by using the added '''<code>print</code>''' statement. Furthermore, a '''<code>read</code>''' statement allows the interactive input of a number into a running calculation. In addition to C-style comments, a '''<code>#</code>''' 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 '''<code>last</code>''' variable. ====Extra operators==== The following [[logical operator]]s are additional to those in POSIX bc: && || ! They are available for use in conditional statements (such as within an '''<code>if</code>''' 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 <code>^</code> 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=== <syntaxhighlight lang="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) ) ) } </syntaxhighlight> ===Calculating Ο to 10000 digits=== Calculate [[pi]] using the builtin [[Inverse trigonometric functions|arctangent]] function, {{mono|a()}}: <syntaxhighlight lang="console" highlight="3"> $ 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. </syntaxhighlight> ===A translated C function=== Because the syntax of bc is similar to that of [[C (programming language)|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 [[normal distribution|cumulative normal distribution]]: <syntaxhighlight lang="c"> 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); } </syntaxhighlight> 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: <syntaxhighlight lang="bc"> define phi(x) { auto s,t,b,q,i,const s=x; t=0; b=x; q=x*x; i=1 while(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) } </syntaxhighlight> ==Using bc in shell scripts== bc can be used non-interactively, with input through a [[Pipeline (Unix)|pipe]]. This is useful inside [[shell script]]s. For example: <syntaxhighlight lang="console"> $ result=$(echo "scale=2; 5 * 7 /3;" | bc) $ echo $result 11.66 </syntaxhighlight> In contrast, note that the [[Bash (Unix shell)|bash shell]] only performs integer arithmetic, e.g.: <syntaxhighlight lang="console"> $ result=$((5 * 7 /3)) $ echo $result 11 </syntaxhighlight> One can also use the [[Here document|here-string]] idiom (in bash, ksh, csh): <syntaxhighlight lang="console"> $ bc -l <<< "5*7/3" 11.66666666666666666666 </syntaxhighlight> ==See also== * [[dc (computer program)|dc programming language]] * [[C (programming language)|C programming language]] * [[hoc (programming language)|hoc programming language]] ==References== {{Reflist}} {{Refbegin}} * {{man|cu|bc|SUS|arbitrary-precision arithmetic language}} * [https://www.gnu.org/software/bc/manual/html_mono/bc.html GNU bc manual page] * [https://web.archive.org/web/20090501204511/http://manpages.ubuntu.com/manpages/jaunty/en/man1/bc.1posix.html POSIX bc manual page] * {{man|1|bc|Plan 9}} * [http://plan9.bell-labs.com/7thEdMan/vol2/bc 7th Edition Unix bc manual page] {{Webarchive|url=https://web.archive.org/web/20061008193920/http://plan9.bell-labs.com/7thEdMan/vol2/bc |date=2006-10-08 }} * [http://compilers.iecc.com/comparch/article/95-09-015 A comp.compilers article on the design and implementation of C-bc] * [http://minnie.tuhs.org/cgi-bin/utree.pl?file=V6/usr/source/s1/bc.y 6th Edition Unix bc source code], the first release of bc, from May 1975, compiling bc syntax into dc syntax * [http://ftp.gnu.org/gnu/bc/ GNU bc source code] {{Refend}} ==External links== {{Wikibooks|Guide to Unix|Commands}} * [https://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–11.] * [http://www.phodd.net/gnu-bc/ Collection of useful GNU bc functions] * [https://www.gnu.org/software/bc/ GNU bc] (and an [http://alpha.gnu.org/gnu/bc/ alpha version]) from the Free Software Foundation * [https://web.archive.org/web/20160222234922/http://gnuwin32.sourceforge.net/packages/bc.htm bc for Windows] from [[GnuWin32]] * [https://git.yzena.com/gavin/bc Gavin Howard bc] - another open source implementation of bc by Gavin Howard with GNU and BSD extensions * [https://web.archive.org/web/20160304084708/http://x-bc.sourceforge.net/ X-bc] - A Graphical User Interface to bc ** [https://web.archive.org/web/20160304092132/http://x-bc.sourceforge.net/extensions_bc.html extensions.bc] - contains functions of trigonometry, exponential functions, functions of number theory and some mathematical constants ** [https://web.archive.org/web/20160304081309/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 {{Unix commands}} {{Plan 9 commands}} [[Category:Software calculators]] [[Category:Cross-platform free software]] [[Category:Free mathematics software]] [[Category:Numerical programming languages]] [[Category:Standard Unix programs]] [[Category:Unix SUS2008 utilities]] [[Category:Plan 9 commands]]
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)
Pages transcluded onto the current version of this page
(
help
)
:
Template:Cite web
(
edit
)
Template:Code
(
edit
)
Template:Infobox
(
edit
)
Template:Infobox software
(
edit
)
Template:Lowercase
(
edit
)
Template:Main other
(
edit
)
Template:Man
(
edit
)
Template:Mono
(
edit
)
Template:More footnotes
(
edit
)
Template:Not to be confused with
(
edit
)
Template:Plan 9 commands
(
edit
)
Template:Refbegin
(
edit
)
Template:Refend
(
edit
)
Template:Reflist
(
edit
)
Template:Samp
(
edit
)
Template:Short description
(
edit
)
Template:Sister project
(
edit
)
Template:Template other
(
edit
)
Template:Unix commands
(
edit
)
Template:Webarchive
(
edit
)
Template:Wikibooks
(
edit
)