Tuesday, June 4, 2019

bash floating point arithmetic evaluation

I need to take two variables and produce a sum.

y=2.0
millDiameter=.75

how do I produce $y+($millDiameter/2.0)

bc, expr, $((arithmetic)) all fail.

I figured it out (not enough caffeine this morning).  test=`echo "200.0/1.5" | bc`

And yet ystart=`echo "$millRadius" | bc`

where millRadius is .375, works on bash line, but produces
syntax error near unexpected token '|' 
in the script.

Unmatched ` and "

4 comments:

Rick C said...

Clayton, try this:
rick@resonance:~$ v=$(echo "y=2.0;m=0.75;y+(m/2.0)" | bc -l)
rick@resonance:~$ echo $v
2.37500000000000000000

You need the -l for the floating-point division to work properly; otherwise v is set to 2.0.

Clayton Cramer said...

Rick: thanks but adding -l gives syntax error and does not seem to be needed for floats.

Rick C said...

I've gotten to where I use $() instead of ``; it helps with the mismatched quotes.

As for your claim that -l didn't work, that was weird, but I don't have linux system handy at the moment so I used Ubuntu 18.04.2 LTS under WSL, and the example I gave was tested and worked for me. Go figure. To clarify my first comment, without the -l, bc seemed to do the division, truncate the result to an integer, and then convert the integer to a float:

rick@resonance:~$ echo $(echo "y=2.0;m=0.75;y+(m/2.0)" | bc -l)
2.37500000000000000000
rick@resonance:~$ echo $(echo "y=2.0;m=0.75;y+(m/2.0)" | bc)
2.0

I don't have an explanation for why it worked differently for me.

Clayton Cramer said...

Rick: -l was needed for one of the calculations but not the other and both were floating point.