Linux bc 命令简单学习

1. bash里面能够实现比较简单的四则运算

echo $((10*20))

注意是 双括号+ $ 地址符号. 

2. 但是比较复杂的 可能就难以为继了 比如不支持精度 

3. 所以这里面需要使用 bc 命令来执行相关的操作. 

man 内容:

usage: bc [options] [file ...]
-h --help print this usage and exit
-i --interactive force interactive mode
-l --mathlib use the predefined math routines
-q --quiet don't print initial banner
-s --standard non-standard bc constructs are errors
-w --warn warn about non-standard bc constructs
-v --version print version information and exit

4. 实现简单的 测试:

使用 bc -l 进入 计算界面:

比如我输入的 sqrt(100) 就是计算100 的平方根了

但是我没找到怎么去立方根

还可以计算 自然对数

比如:

l(10) 表示 以 e为底 10 的对数
e(10) 表示 e 的10次方...

5. 但是这样计算可能不太方便 也可以使用 管道命令执行相应的操作:

求直接三角形的 第三条边的长度.

echo "ibase=10,obase=2,254" |bc -l -q

6. 或者是可以实现 进制的转换:

echo "ibase=10;obase=2;254" |bc -l -q

 7. 总结语法注意点:

每个参数 使用 分号 分隔 可以使用 管道 也可以不使用管道. 

8. 数学函数

   MATH LIBRARY
       If bc is invoked with the -l option, a math library is preloaded and the default scale is set to 20.   The math functions will calculate their results to the scale set at the time of their call.  The math library defines the following functions:

       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.

so 可以显示圆周率的 公式是 

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

显示自然对数的公式

echo "scale=10;e(1)" |bc -l -q

猜你喜欢

转载自www.cnblogs.com/jinanxiaolaohu/p/10637702.html