Dc versus bc

From Noah.org
Revision as of 19:44, 6 December 2007 by Root (Talk | contribs)

Jump to: navigation, search

Q: What is the difference between `dc` and `bc`?

A: The `dc` command is a Reverse-Polish Notation basic arithmetic calculator. It does not support common trigonometric or scientific functions. Examples of `dc`:

 $ dc -e "25.5 2 * p"
 51.0
 $ dc -e "3 2 ^ p"
 9
 $ dc -e "9 v p"   # Note that 'v' is the sqrt operator.
 3

The `bc` command is a front-end to `dc` (althugh the GNU `bc` is completely separate and does not compile to `dc` bytecode). So `bc` is similar to `dc`, but adds a C-like syntax; standard infix notation. By default it does not include trig or other common math functions, but you include these by using the '-l' option. Examples of `bc`:

 $ echo "scale=5; 10 / (1.5 * 2)" | bc   # Note that you have to set scale to see decimals.
 3.33333
 $ echo "10 / (1.5 * 2)" | bc   # The default scale is 0.
 3
 $ echo "10 / (1.5 * 2)" | bc -l   # Note that '-l' option automatically sets scale to 20.
 3.33333333333333333333
 $ echo "4*a(1)" | bc -l   # Note that 'a' is the arctangent function.
 3.14159265358979323844

Using bc in bash

Trying to do even trivial math with `expr` is a pain. Bash sucks. To set a variable to an expression you end up having to write code like this:

SIZE_MB=$(bc <<< '50000000/(1024*1024)')