Question

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.

Était-ce utile?

La solution

I usually call bc -l if I need floating point numbers.

Autres conseils

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)
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top