I have a bash array of floating point numbers, say it is called vals
and intialized like this --
# load data from the datafile.txt
vals=`cat datafile.txt`
vals=($vals)
The datafile.txt
looks like this --
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 --
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
.
any idea?
EDIT : The data are changed.
Use scale
to define the amount of digits after the decimal point:
$ 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
:
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
。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.