In this post, we will cover how to do advanced arithmetic and write your own functions with GNU bc.
If you are looking at doing basic arithmetic in a bash shell or using bc, you should take a look at my older post about Performing Math Calculation in Bash.
About GNU bc
bc stand for basic calculator, it was preceded by dc, a cross-platform reverse-polish desk calculator one of the oldest Unix utilities.
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.
Math Library Functions
Using the -l option of the GNU bc command line utility will load the Math library and set the default value of scale to 20. The predefined functions that comes with the math library are:
The sine of x, x is in radians.
The cosine of x, x is in radians.
The arctangent of x, arctangent returns radians.
The natural logarithm of x.
The exponential function of raising e to the value x.
The bessel function of integer order n of x.
GNU bc provide few special expressions that make it even more powerful.
length ( expression )
The value of the length function is the number of significant digits in the expression.
read ( )
read function (an extension) will read a number from the
standard input, regardless of where the function occurs. Beware, this
can cause problems with the mixing of data and program in the standard
input. The best use for this function is in a previously written
program that needs input from the user, but never allows program code to
be input from the user. The value of the
read function is the
number read from the standard input using the current value of the
variable ibase for the conversion base.
scale ( expression )
The value of the
scale function is the number of digits after the
decimal point in the expression.
sqrt ( expression )
The value of the
sqrt function is the square root of the
expression. If the expression is negative, a run time error is
Going further: Write a function
GNU bc allows you to define your own Functions and makes the language very powerful.
There is a wide list of open source projects with a lot of functions available. You should check all the X-BC resources.
- extensions.bc: contains functions of trigonometry, exponential functions, functions of number theory and some mathematical constants.
- scientific_constants.bc: contains particle masses, basic constants, such as speed of light in the vacuum and the gravitational constant.
Another amazing resource is the GNU bc FAQ on phodd.net. You will find a large amount of functions in the file funcs.bc that can be of a good help and gives you some good examples (include round-up, ceil, floor, etc).
To go further, I highly recommend reading the GNU bc Manual.