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?

Jeff Schaller
  • 66,199
  • 35
  • 114
  • 250
Black Heart
  • 103
  • 2
  • Related: [How to sum a bash array of numbers (some in scientific notation)?](https://unix.stackexchange.com/questions/99092/how-to-sum-a-bash-array-of-numbers-some-in-scientific-notation) – steeldriver Apr 08 '19 at 13:45
  • Thanks. Didn't know its different for scientific notation – Black Heart Apr 08 '19 at 13:50

3 Answers3

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}'`
Romeo Ninov
  • 16,541
  • 5
  • 32
  • 44
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

Siva
  • 9,017
  • 8
  • 56
  • 86
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)