代碼中免不了要進行各種數據計算。拋開科學計算不提,普通的計算占地,百分比,同比,環比等需求就很常見。linux shell中進行數字計算,主要有如下幾種方式:
[code][webopa@namenode-backup expensive_user]$ a=`echo 1+1 | bc` [webopa@namenode-backup expensive_user]$ echo $a 2
但是浮點數運算的精度問題,暫時還沒明白什麼情況:
[code][webopa@namenode-backup expensive_user]$ b=`echo "1.2*1.2" | bc` [webopa@namenode-backup expensive_user]$ echo $b 1.4 [webopa@namenode-backup expensive_user]$ c=`echo "5.0/3.0" | bc` [webopa@namenode-backup expensive_user]$ echo $c 1 [webopa@namenode-backup expensive_user]$ d=`echo "scale=2;5.0/3.0" | bc` [webopa@namenode-backup expensive_user]$ echo $d 1.66 [webopa@namenode-backup expensive_user]$ e=`echo "scale=2;5.0/6.0" | bc` [webopa@namenode-backup expensive_user]$ echo $e .83尤其最後一個,這到底什麼鬼,小數點前的那個0跑哪裡去了。。。
[code][webopa@namenode-backup expensive_user]$ a=`expr 1+1` [webopa@namenode-backup expensive_user]$ echo $a 1+1 [webopa@namenode-backup expensive_user]$ a=`expr 1 + 1` [webopa@namenode-backup expensive_user]$ echo $a 2 [webopa@namenode-backup expensive_user]$ b=`expr 10 / 2` [webopa@namenode-backup expensive_user]$ echo $b 5
[code][webopa@namenode-backup expensive_user]$ a=$((1+1)) [webopa@namenode-backup expensive_user]$ echo $a 2 [webopa@namenode-backup expensive_user]$ b=$((1 + 3 )) [webopa@namenode-backup expensive_user]$ echo $b 4
[code][webopa@namenode-backup expensive_user]$ let a=1+1 [webopa@namenode-backup expensive_user]$ echo $a 2 [webopa@namenode-backup expensive_user]$ let b=50/5 [webopa@namenode-backup expensive_user]$ echo $b 10 [webopa@namenode-backup expensive_user]$ let c=1.2*2 -bash: let: c=1.2*2: syntax error: invalid arithmetic operator (error token is ".2*2")
[code][webopa@namenode-backup expensive_user]$ a=`echo | awk '{print 1.0/2.0}'` [webopa@namenode-backup expensive_user]$ echo $a 0.5
控制精度:
[code][webopa@namenode-backup expensive_user]$ b=`echo | awk '{printf("%.2f",1.0/2.0)}'` [webopa@namenode-backup expensive_user]$ echo $b 0.50傳遞參數:
[code][webopa@namenode-backup expensive_user]$ c=`echo | awk -v a=1 -v b=3 '{printf("%.4f",a/b)}'` [webopa@namenode-backup expensive_user]$ echo $c 0.3333綜合來看,還是awk最靠譜,其他的方式都有這樣那樣的問題。所以我平時一般都用awk來搞數學計算。