0

I'm trying to add two doubles

y1=0.17580197E-01
y2=0.11979236E-02
sum=`echo $y1+$y2 | bc -l`

the above script gives me sum = -2.704405652. How do i resolve this issue?

2
0

You can do it with awk with this command:

sum=`echo|awk -v y1=$y1 -v y2=$y2 '{print y1+y2}'`

As suggested in comment awk can be rewritten on this way (to avoid echo)

sum=`awk -v y1=$y1 -v y2=$y2 'BEGIN {print y1+y2}'`
0
0

Try this,

echo "$y1 $y2" | awk  '{print $1+$2}'
0.0187781

Just print the two values separated by space and add the first two fields with awk

0

To add with bc the numbers should not have the scientific exponent. In other words, the numbers should be in float (%f) format. That could be done with:

y1=0.17580197E-01
y2=0.11979236E-02
sum=$(printf '%.20f+%.20f\n' "$y1" "$y2" | bc -l)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.