代码改变世界

Linux小工具bc使用

2014-01-08 09:16  Ryan_Liu  阅读(1060)  评论(0编辑  收藏  举报

现在才知道bc竟然是可以编程的,不得不佩服linux各种工具的博大精深(推荐一本书,software tools

man bc,bc可加的参数有 bc [ -hlwsqv ],其中我们常用的也就是-l了,它的意思是定义一些常用的数学库,比如log,sin之类的,所以一般打开bc的命令为bc -l

常用的数学运算的书写方式

s (x) The sine of x, x is in radians.

c (x) The cosine of x, x is in radians.

a (x) The arctangent of x, arctangent returns radians.

l (x) The natural logarithm of x.

e (x) The exponential function of raising e to the value x.

j (n,x)
The Bessel function of integer order n of x.

至于这个Bessel function,目前我还没有接触过,我想一些学数学的可能用的比较多吧。

 

man中还给出了一个在bash中,用bc赋值的例子

pi=$(echo "scale=10; 4*a(1)" | bc -l)

用反正切函数求pi,数学真的很神奇

 

bc的语法和C语言差不多,给个喜闻乐见的计算阶乘的例子吧

define f(x) {
  if (x <= 1) return (1);
  return (x*f(x-1));
}

 

再给一个计算兔子生孩子(-_-)的例子,来说明数组的使用,毕竟很多时候我们还是懒得写函数的

h[1]=1
h[2]=1
for (i=3;i<=100;i++)
  h[i]=h[i-1]+h[i-2]


for (i=1; i<=100; i++) {
  print h[i],"       ";
  if (i%10==0) print "\n;"
}

另外数组下标是可以从0开始的