User Tools

Site Tools


bc_calculator

bc

Few Samples to understand usage

How it looks..

| command
desk:~/# bc 
2048 * 3
6144
256 * 6
1536
quit

Simple calculation

echo "56.8 + 77.7" | bc

Calculation with floating point

echo 2/5 | bc -l
bc -l works, but it sets scale=20 which gives:
1/3
.33333333333333333333
most of the time I just want two decimal places.
 
there may be an easier way, but what works for me is the following:
in .bashrc in your home directory add BC_ENV_ARGS=~/.bc
export BC_ENV_ARGS
then create .bc also in your home directory
with one line
scale=2
then when bc is run
1/3
.33

Ibase is input base, and obase is output base, by specified the base, you can convert number from one base to another.

echo "obase=16; ibase=10; 56" | bc

To perform division is a bit tricky, because the will result usually in floating point. Therefore in order to get the correct answer, you need to specified scale. scale means the precision of floating point, how many digit after the point. By default the scale is 0, that means it is integer. 5.00500 - the scale is 5

echo "scale=6;  60/7.02" | bc
 I also use “prepend” to deal with pipeline problems that occur. For example:
 
tester@desk ~/test $ echo “13203903″ | prepend “obase=2;ibase=10;” | bc
110010010111100110111111
 
Otherwise, you can’t enter the obase/ibase stuff without messing up the pipeline.
 
But as for bc, I don’t use it much, and prefer my “pc” perl calculator. It does normal math, but I mostly use it for advanced financial calculations.
 
tester@desk /usr/src $ pc
Entering interactive mode, use “expression” to run in batch mode.
>1000000=50000(F/P,i%,30)
Result: 0.105013847351074 @ 1000003.71937184, aiming for 1000000
10.50%
 
Interpreted: Find the interest rate ‘i’ for which the ‘F’uture value is 1 million given a ‘P’resent value of $50,000 invested for 30 years.
bc_calculator.txt · Last modified: 2020/08/10 02:35 (external edit)