XXX
分类: LINUX
2014-04-01 05:11:59
原文地址:使用bc进行浮点运算 作者:xjc2694
Bash 不能处理浮点运算, 并且缺乏特定的一些操作,这些操作都是一些重要的计算功能.幸运的是, bc 可以解决这个问题.bc 不仅仅是个多功能灵活的精确的工具, 而且它还提供许多编程语言才具备的一些方便的功能. 因为它是一个完整的 UNIX 工具, 所以它可以用在中, bc 在脚本中也是很常用的.
这里有一个简单的使用 bc 命令的模版可以用来在计算脚本中的变量. 用在命令替换 中.
variable=$(echo "OPTIONS; OPERATIONS" | bc)
如:interest_rate=$(echo "scale=9; $interest_r/12 + 1.0" | bc)
An alternate method of invoking bc involves using a here document embedded within a block. This is especially appropriate when a script needs to pass a list of options and commands to bc.
1 variable=`bc << LIMIT_STRING 2 options 3 statements 4 operations 5 LIMIT_STRING 6 ` 7 8 ...or... 9 10 11 variable=$(bc << LIMIT_STRING 12 options 13 statements 14 operations 15 LIMIT_STRING 16 ) |
Example 12-44. Invoking bc using a "here document"
1 #!/bin/bash 2 # Invoking 'bc' using command substitution 3 # in combination with a 'here document'. 4 5 6 var1=`bc << EOF 7 18.33 * 19.78 8 EOF 9 ` 10 echo $var1 # 362.56 11 12 13 # $( ... ) notation also works. 14 v1=23.53 15 v2=17.881 16 v3=83.501 17 v4=171.63 18 19 var2=$(bc << EOF 20 scale = 4 21 a = ( $v1 + $v2 ) 22 b = ( $v3 * $v4 ) 23 a * b + 15.35 24 EOF 25 ) 26 echo $var2 # 593487.8452 27 28 29 var3=$(bc -l << EOF 30 scale = 9 31 s ( 1.7 ) 32 EOF 33 ) 34 # Returns the sine of 1.7 radians. 35 # The "-l" option calls the 'bc' math library. 36 echo $var3 # .991664810 37 38 39 # Now, try it in a function... 40 hyp= # Declare global variable. 41 hypotenuse () # Calculate hypotenuse of a right triangle. 42 { 43 hyp=$(bc -l << EOF 44 scale = 9 45 sqrt ( $1 * $1 + $2 * $2 ) 46 EOF 47 ) 48 # Unfortunately, can't return floating point values from a Bash function. 49 } 50 51 hypotenuse 3.68 7.31 52 echo "hypotenuse = $hyp" # 8.184039344 53 54 55 exit 0 |