bash + 用bash进行算术计算

bash + 用bash进行算术计算

我需要用 bash 执行以下操作,优雅的方法是什么?得到最终的 $sum 值

worker_machine=32
executors_per_node=3

executer=$worker_machine/$executors_per_node-1
spare=$executer X 0.07 
sum=$executer-$spare ( with round the number to down ) 

example:

32/3 = 10 - 1 = 9
9 X 0.7 = 0.6
9 – 0.6 = 8 ( with round the number to down ) 

答案1

使用awk,从 shell 变量中获取值:

awk -v n="$worker_machine" -v m="$executors_per_node" \
    'BEGIN { printf("%d\n", 0.93 * (n / m - 1)) }' /dev/null

awk脚本不会像往常一样获取任何输入,因此我们使用/dev/null作为输入文件并在块中进行计算和输出BEGIN

使用bc

sum=$( printf '0.93 * (%d / %d - 1)\n' "$worker_machine" "$executors_per_node" | bc )
printf '%.0f\n' "$sum"

使用dc

sum=$( printf '%d\n%d\n/\n1\n-\n0.93\n*\np\n' "$worker_machine" "$executors_per_node" | dc )
printf '%.0f\n' "$sum"

答案2

shell 能够进行数学运算(作为整数,向下舍入):

$ sum=$(( ( worker_machine/executors_per_node-1 ) * 93 / 100 ))
$ echo "$sum"
8

bc 的默认小数位数是 0,因此除法的结果将是整数:

$ sum=$(bc <<<"($worker_machine / $executors_per_node - 1)*93/100")
$ echo "$sum"
8

由于我们想要一个整数,我们可以向 awk 请求一个整数

$ sum=$(awk -v m="$worker_machine" -v n="$executors_per_node" 'BEGIN{ print( int((m/n-1)*93/100) )}' /dev/null)
$ echo "$sum"
8

相关内容