关于Linux命令行下的数学运算示例详解

2019-10-10 10:47:47丽君

#!/bin/bash

echo -n "Cost to us> "
read cost
echo -n "Price we're asking> "
read price

if [ `expr $price > $cost` == 1 ]; then
 echo "We make money"
else
 echo "Don't sell it"
fi

factor

factor 命令的功能基本与你预期相符。你给出一个数字,该命令会给出对应数字的因子。

$ factor 111
111: 3 37
$ factor 134
134: 2 67
$ factor 17894
17894: 2 23 389
$ factor 1987
1987: 1987

注: factor 命令对于最后一个数字没有返回更多因子,这是因为 1987 是一个 质数 。

jot

jot 命令可以创建一系列数字。给定数字总数及起始数字即可。

$ jot 8 10
10
11
12
13
14
15
16
17

你也可以用如下方式使用 jot ,这里我们要求递减至数字 2。

$ jot 8 10 2
10
9
8
7
5
4
3
2

jot 可以帮你构造一系列数字组成的列表,该列表可以用于其它任务。

$ for i in `jot 7 17`; do echo April $i; done
April 17
April 18
April 19
April 20
April 21
April 22
April 23

bc

bc 基本上是命令行数学运算最佳工具之一。输入你想执行的运算,使用管道发送至该命令即可:

$ echo "123.4+5/6-(7.89*1.234)" | bc
113.664

可见 bc 并没有忽略精度,而且输入的字符串也相当直截了当。它还可以进行大小比较、处理布尔值、计算平方根、正弦、余弦和正切等。

$ echo "sqrt(256)" | bc
16
$ echo "s(90)" | bc -l
.89399666360055789051

事实上, bc 甚至可以计算 pi。你需要指定需要的精度。

$ echo "scale=5; 4*a(1)" | bc -l
3.14156
$ echo "scale=10; 4*a(1)" | bc -l
3.1415926532
$ echo "scale=20; 4*a(1)" | bc -l
3.14159265358979323844
$ echo "scale=40; 4*a(1)" | bc -l
3.1415926535897932384626433832795028841968

除了通过管道接收数据并返回结果, bc 还可以交互式运行,输入你想执行的运算即可。本例中提到的 scale 设置可以指定有效数字的个数。

$ 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=2
3/4
.75
2/3
.66
quit

你还可以使用 bc 完成数字进制转换。 obase 用于设置输出的数字进制。

$ 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'.
obase=16
16  <=== entered
10  <=== response
256  <=== entered
100  <=== response
quit

按如下方式使用 bc 也是完成十六进制与十进制转换的最简单方式之一:

$ echo "ibase=16; F2" | bc
242
$ echo "obase=16; 242" | bc
F2