0

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.

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

1

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.