0

I'm trying to calculate some float numbers in shell with these commands:

zmin='0.004633'          
zmax='3.00642'  
step='0.1'  
echo "zmin=$zmin"        
echo "zmax=$zmax"  
echo "step=$step"  
n=`echo "(($zmax - $zmin)) / $step " |bc -l `  
b=${n/\.*}  
echo "b=$b"  

for ((j = 1; j <= b; j++))  
do  
    z_$j=`echo  "scale=7; (($zmin + $(($j-1)))) * $step" |bc -l`  
    zup_$j=`echo  "scale=7; $((z_$j)) + $step " |bc -l `  
    echo "z_$j=$((z_$j)) && zup_$j=$((zup_$j))"
done

but I just receive the correct answer for n. For z_$j & zup_$j I'm receiving this error:

'z_9=.8004633: command not found'  

How I can solve this problem?

2
  • 3
    Is there any reason you're using Bash for this? It's just not appropriate. Use python, or any number of other tools that can handle floating point arithmetic. The people that have to maintain your code will thank you. You can even use bc to do all the looping, so perhaps write the entire thing as a single bc command. Commented Aug 26, 2013 at 12:18
  • 1
    The shell's not going to let you parameterize the l.h.s. of an environment variable set. Commented Aug 26, 2013 at 12:28

1 Answer 1

1

Your problem isn't floating-point, it's that you can't build a variable name like this. If you were using a strict POSIX shell, you would need to use eval to do this:

tmp=$( echo "scale=7; ( $zmin + $j - 1 ) * step" | bc -l )
eval "z_$j=$tmp"

However, the for loop you are using is not a POSIX feature, which implies you are using bash or some other shell that also supports arrays, so you should use one.

for ((j=1; j<=b; j++))
do
    z[j]=$( echo "scale=7; ( $zmin + $j - 1 ) * $step " | bc -l )
    zup[j]=$( echo "scale=7; ${z[j]} + $step" | bc -l )
    echo "z[$j]=${z[j]} && zup[$j]=${zup[j]}"
done
Sign up to request clarification or add additional context in comments.

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.