===== GNU bc Cheat Sheet ===== ==== Overview ==== * [[http://en.wikipedia.org/wiki/Bc_programming_language | bc ]] is a command-line calculator and primitive language * bc is a [[http://www.opengroup.org/onlinepubs/009695399/utilities/bc.html |POSIX standard]] but the [[http://www.gnu.org/software/bc/ | GNU version]] has added functionality * bc by default runs in integer mode (scale=0) and with no trig functions, running ''bc -l'' loads trig functions and sets scale to 20 * bc can only take expressions on standard input or in files, not directly on the command line. One way to do a bc one-liner is ''echo 3+4 | bc'' . * [[http://www.phodd.net/cyrek/gnu-bc/ | This]] is a great collection of bc functions. funcs.bc and logic.bc are the basic ones. [[ http://x-bc.sourceforge.net/extensions_bc.html | This]] is a collection of more sanely named basic scientific calculator functions. * useful bash aliases mbc () { echo $@ | bc -l -q ~/bin/extensions.bc } alias bc="bc -l -q ~/bin/extensions.bc" So now '' mbc '(3+5)/6' '' works as expected * bc uses readline so ⇑ and ⇓ (for history) and ctrl-r (for searching) work as expected. ==== Basic Usage ==== * Any alphanumeric variable name is allowed once it starts with a letter. * There are 4 special variables * ''last'' - The value of the last printed number * ''scale'' - number of decimal places to display * ''ibase'' - base to be used for input values * ''obase'' - base to be used for output values * Any expression that is not an assignment is displayed and stored in the ''last'' variable. * Every value and every expression is a number. The assignment operator returns 0. Booleans are 0 / 1. * Basic + - / * = == work. % is modulo . ^ is integer exponentiation. * Predefined functions are : * s - sine , c - cosine * a - arctan , j(n,x) - Bessel function * l - natural log , e - e to the power of * length, scale, sqrt - as named * && , || , ! work as expected (return 0 or 1). ==== Advanced Usage ==== * New functions are easy to define e.g. define log(x,y) { auto retval = l(y)/l(x) return retval } Note that the ''auto'' keyword is used to declare a local variable. * ''if(cond) else'', ''while(cond)'' and ''for(init;cond;inc)'' control flow structures are all supported. ''break'' and ''continue'' are also supported. * ''read()'' is used to read a value from standard input. ''print()'' prints to standard output. * Arrays can be used by using ''[subscript]'' after the array name. * Special commands include ''quit'', ''limits'' and ''warranty''.