effeffe
effeffe

Reputation: 2881

C-like for loop with float values and bc, unexpected ";"

I'm a bash beginner and I can't spot the error in this loops, and bash just gives me syntax error: ';' unexpected, not really useful...

# log2(x) = ln(x) / ln(2)
for (( j=$(echo "l($i) / l(2)" | bc -l) ;
    $(echo "scale=$SCALE; j < (2*$i)" | bc) == 1 ;
    j=$(echo "scale=$SCALE; $j + 1/$step" | bc) ))
do
        foo...
done

What I want to do is something like this, using a C-like pseudo-code:

integer i

for ( float j = log2(i) ; j < 2*i ; j += 1/8 )
    ...

Maybe there are better ways to do this, I don't know. Can't find anything here or on Google... well, it's hard to find a solution searching "syntax error".

Upvotes: 0

Views: 328

Answers (1)

ruakh
ruakh

Reputation: 183290

The for (( ... )) notation expects shell arithmetic notation, not regular Bash commands. (I mean, shell arithmetic does support expansions such as $(...), but that's a recipe for total confusion.) Since shell arithmetic won't work for you (it's only for integers), you're better off using a while-loop, something like this:

j=$(bc -l <<< "l($i) / l(2)")
while [[ $( bc <<< "scale=$SCALE; $j < 2 * $i" ) = 1 ]] ; do
    ...
    j=$(bc <<< "scale=$SCALE; $j + 0.125")
done

Upvotes: 3

Related Questions