[TOC]

浮点运算

输入:整数,letexpr都无法进行浮点运算,但是bcawk可以

输出:bc、expr可直接显示计算结果;let则丢弃计算结果,可通过传递结果到变量,取变量值获得计算结果。

bc&awk

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#法一: 
#!/bash
for((i=1;i<=10;i++))
do
  echo $i
  j=$(echo "$i*0.2-2.5"|bc)
  echo $j
done

# 法二:
#!/bash
for((i=1;i<=10;i++))
do
  echo $i
  j=`bc <<< "0.2*(${i}-1)-2.5"`
  echo $j
done

#法三:scale 对乘法无效
$ echo "scale=3; 1/13" | bc
.076
$ echo "1 13" | awk '{printf("%0.3f\n",$1/$2)}'
0.077
#scale用来控制小数点后面保留的位数

实例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#!/bin/bash
# author: Jay <smile665@gmail.com>
# some examples for playing with floating point number.

# basic usage of 'bc' tool in Bash.
a=3.33
b=3.3
c=$(echo "$a + $b" | bc)
d=$(echo "$a * $b" | bc)
e=$(echo "scale=5; $a / $b" | bc)
echo "c=a+b=$a+$b=$c"
echo "d=a*b=$a*$b=$d"
echo "e=a/b=$a/$b=$e"

# "-l" parameter for 'bc' means using math library.
pi=$(echo "scale=10; 4*a(1)" | bc -l)
s=$(echo "s($pi/6)" | bc -l)
echo "pi=$pi"
echo "s=sin(pi/6)=$s"

# use more options of 'bc' tool
r=$(echo 'ibase=10;obase=2; 15+16' | bc)
echo "binary of (15+16) is $r"

# comparison for floating point numbers using 'bc'
big=100
small=99.9
if [ $(echo "$big > $small" | bc) -eq 1 ]; then
echo "$big is bigger than $small"
fi

# deal with floating point numbers with 'awk' language
echo $(awk -v x=10 -v y=2.5 'BEGIN {printf "10/2.5=%.2f\n",x/y}')
v=$(echo $big $small | awk '{ printf "%0.8f\n" ,$1/$2}')
echo "$big / $small = $v"

echo $big $small | awk '{if($1>$2) {printf"%f > %f\n",$1,$2} else {printf"%f <%f\n",$1,$2}}'
1
2
3
4
5
6
7
8
9
10

master@jay-linux:~/workspace/mygit/shell/sh2012$ cat temp.bc
3+8
3/8
scale=2; 3/8

master@jay-linux:~/workspace/mygit/shell/sh2012$ bc -q temp.bc
11
0
.37

bc是强大的工具,请“man bc”查看详情;同样,请“man awk”。

参考:

https://www.jb51.net/article/50642.htm