Monday, February 20, 2012

bc - the commandline calculator

PS: This is an old post. Waste of time. Get python.
As most of the linux users already know, there is a command line calculator (actually, its a scripting language) in linux that can be invoked from the shell by typing bc. It is an arbitrary precision calculator that can calculate such huge numbers like 2^1000 and print it correctly to the last digit.
It supports the operators +,-,*,/  & ^(exponentiation). It has a minimal math library that can be accessed by a -l option. But it only supports 6 functions: sine,cosine,ln, atan, e^x and Bessel's function.
But most of the other functions can be calculated using these functions by the help of a few mathematical identities. Here is a code snippet I use to increase the utility of bc.


pi=3.141592653589793

#s(x) is sine in standard math lib
define sin(x)
{ return (s(x)); }

#c(x) is cosine in standard math lib
define cos(x)
{ return (c(x)); }

define tan(x)
{ return (s(x)/c(x)); }

#l(x) from std math lib
define ln(x)
{ return (l(x)); }

define log10(x)
{ return (l(x)/l(10)); }

#a(x) from standard math lib
define atan(x)
{ return (a(x)); }

define asin(x)
{
  if(x==1)
  return (pi/2);
  if(x>=0)
  return (a(x/sqrt(1-x^2)));
  if(x==-1)
  return (-1*pi/2);
  if(x<0)
  return (-1*(a(x/sqrt(1-x^2)))); }

define acos(x)
{ return (pi/2-asin(x)); }

define factorial(x)
{ i=1; prod=1;
  for(i=1;i<=x;i++)
  prod=prod*i;
  return (prod);
}


To use it put it in a text file in your home directory and save it as "lib". From terminal, change to home and type
bc -l lib


Now you can use the functions: sin(), cos(), tan(), ln(), log10(), atan(), asin(), acos() and factorial(). You can implement your own functions too. Just look up info bc on terminal. The syntax of bc is almost same as that of C, so if you know C its easier to learn bc.

For windows users, bc is available from  http://sourceforge.net/projects/gnuwin32/files/bc/1.06-2/bc-1.06-2.exe/download

PS: This is an old post. Waste of time. Get python.

No comments:

Post a Comment