Tuesday, June 4, 2019

bash floating point arithmetic evaluation

I need to take two variables and produce a sum.


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 "


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

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

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

  3. 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)
    rick@resonance:~$ echo $(echo "y=2.0;m=0.75;y+(m/2.0)" | bc)

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

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