Sunday, January 1, 2012

bc - a powerful calculator

"An arbitrary precision calculator language' - this is what the man page says. This is fairly a simple tool in term of usage.
For instance :- Just type in "bc" in your shell prompt and you have the tool running.

Code:
root@bt > 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'.

22/7
3

See the "22/7", that is what I have typed in and there is the result. You can also use this like an one liner.

Code:
root@bt > echo " 22/7 " | bc
3

Hmmm I know, the decimals are missing right? No problem, we just need to tell the "bc" to print the decimals. Use "scale" for that purpose.

Code:
root@bt > echo " scale=5; 22/7 " | bc
3.14285


Wow! happy now? ;)

If you go thru the man page, you can see that whatever you do in C using the math lib, you can do it using "bc" as well. What got my attention is that, we can actually have our own functions written and call it.

Code:
root@bt > echo "define foo(a,b){ return a+b }; print foo(10,20)" | bc
30

Cool right? I mean look at the flexibility this small tool is providing you. Well, can't call this a small tool now, can we?
Just for information, I found another program "calc".

Code:
root@bt > calc
C-style arbitrary precision calculator (version 2.12.3.3)
Calc is open software. For license details type:  help copyright
[Type "exit" to exit, or "help" for help.]

; 22/7
~3.14285714285714285714
;

Check this out!

Code:
root@bt > 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'.

scale=100
22/7
3.142857142857142857142857142857142857142857142857142857142857142857\
1428571428571428571428571428571428

I did try with a scale of 1000 and it worked!


Good Day!

No comments:

Post a Comment