简体   繁体   English

将bash数组值传递给bc

[英]passing bash array values to bc

I have a bash array of floating point numbers, say it is called vals and intialized like this -- 我有一个bash浮点数数组,说它叫做vals ,像这样初始化-

# load data from the datafile.txt

vals=`cat datafile.txt` 
vals=($vals)

The datafile.txt looks like this -- datafile.txt看起来像这样-

0.012256791324227446
0.012424287090558156
0.013912725724889032
0.014678182257134693

Now I need to calculate the average of element 1 and 2 in vals using bc, I am doing as follows -- 现在我需要使用bc计算vals中元素1和2的平均值,我正在做以下事情-

result=$(echo "(${vals[1]} + ${vals[2]})/2.0" | bc)
echo result: $result

but the result is always 0 , please note that the elements are not 0.0 . result始终为0 ,请注意,元素不是0.0

any idea? 任何想法?

EDIT : The data are changed. 编辑:数据已更改。

Use scale to define the amount of digits after the decimal point: 使用scale小数点后确定的数字量:

$ echo "scale=5; (${vals[1]} + ${vals[2]})/2.0" | bc
.49580

$ echo "scale=3; (${vals[1]} + ${vals[2]})/2.0" | bc
.495

From man bc : 来自man bc

scale ( expression ) 规模 (表示)

The value of the scale function is the number of digits after the decimal point in the expression. 标度函数的值是表达式中小数点后的位数。


Also, note this suffices: 另外,请注意以下内容:

vals=$(cat datafile.txt)

如果我需要浮点数,通常会打电话给bc -l

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM