LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   cannot add fractions in loop using bc in a script? (https://www.linuxquestions.org/questions/linux-newbie-8/cannot-add-fractions-in-loop-using-bc-in-a-script-788381/)

sonu kumar 02-11-2010 12:03 AM

cannot add fractions in loop using bc in a script?
 
hi dear all

i have tried a lot to add floating values in while loop using bc, but no sucess!!!


script is :

read a1
read a11

b=$(echo "scale=10; $a1/1000" | bc)
c=$b
echo "c is $c"

while [[ $a1 -lt $a11 ]] ; do
c=$(echo "scale=10; $c+0.005" | bc) #
echo "c is $c"
done

output:
....
....
c is 12.7000000000
c is 12.7050000000
...
.....infinite loop?

with regards!!!
skumar

catkin 02-11-2010 12:42 AM

$a1 and $a11 are not changed in the loop so the [[ $a1 -lt $a11 ]] test will always return the same result.

David the H. 02-11-2010 12:42 AM

First of all, please use [code][/code] tags around your code, to preserve formatting and readability.

Second, your while loop doesn't do anything to change the test.
Code:

while [[ $a1 -lt $a11 ]] ; do

    c=$(echo "scale=10; $c+0.005" | bc)

    echo "c is $c"

done

If a1 is less than a11, the loop will continue indefinitely.

chrism01 02-11-2010 01:08 AM

Your problem is that bash only does integer comparisons (even though bc can do float calcs); the usual trick for langs like that is simply to multiply (scale) your actual values up enough to be able to treat them as integer eg if you want increments of 0.1, multiply by 10 and use increments of 1.
You could just use a better lang eg Perl.

sonu kumar 02-11-2010 07:42 AM

Quote:

Originally Posted by chrism01 (Post 3860022)
Your problem is that bash only does integer comparisons (even though bc can do float calcs); the usual trick for langs like that is simply to multiply (scale) your actual values up enough to be able to treat them as integer eg if you want increments of 0.1, multiply by 10 and use increments of 1.
You could just use a better lang eg Perl.

hi chris !!

can you tell/suggest me the good and simple links to learn the perl language.

thanks in advance!!!
Sk

chrism01 02-11-2010 05:24 PM

http://perldoc.perl.org/ - lang definition with loads of examples & extra tutorials
http://www.perlmonks.org/?node=Tutorials - more tutorials

Enjoy
:)


All times are GMT -5. The time now is 02:08 PM.