EmbLogic's Blog

Bench Calculator.

Faced with the limitations of the shell command expr and other shell constructs, let’s set out to explore the powerful command bc, which stands for bench calculator. This is not just a command or tool, but a complete language in itself. And its power lies in its arbitrary preciseness with not only integers, but with real numbers. If you are wondering what that means, its computation is usually not limited by the size of the integer or real number types, unlike in most programming languages. Thus, this is closer to our day-to-day use of mathematics, abstracting away the internal details of the computer’s precision. So, let’s get started with the first bits of math, and then move on to more involved aspects like variables, conditionals, and still later on, functions and recursion.

Basic operations
For integer-only math, you can invoke the bench calculator as bc. For full-fledged real number math, invoke it as bc l. Once invoked, it will print a welcome message and then wait for you to type your math statements, before pressing Enter to get your answer. To quit bc, enter Ctrl-D on an empty line. All the basic arithmetic operations: addition (+), subtraction (-), multiplication (*), quotient (/), remainder (%), power (^), and brackets (()) are just there with C-language-like precedence and associativity rules.

[root@localhost]# bc
bc 1.06.95
Copyright 1991-1994, 1997, 1998, 2000, 2004, 2006 Free Software Foundation, Inc.
This is free software with ABSOLUTELY NO WARRANTY.
For details type `warranty'.
2 + 2 * 3 - 5 + 21 / 4 * 6 # A basic maths statement
33
(2 ^ 2) ^ 3 # Another one, with power & brackets
64
^D

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>