Shell Scripts and Floating Point Arithmetic

Associate
Joined
6 Nov 2006
Posts
722
Location
Devon
I have a script file which contains the following:

Code:
START=-0.0004078266210854053
END=0.001179981511086226
DIFF=$(($END - $START))

for i in $(seq -w 0 10)
	j=$(($START +$DIFF\*$i/10))
	./eqlat.out $j > dump${i}
done

Now this code doesn't work and from some googling it seems that the bash shell doesn't support floating point arithmetic. I tried using dtksh but the script file won't run at all then; it just says command not found. What's the best way to get this simple floating point arithmetic working?

Thanks
 
It doesn't have to be bash but like I said i tried to use Korn93 but it doesn't seem to like that either. I just tried to use bash as I'm a linux newbie and bash is the one the examples I looked at were in.

I'll take a look at that link
 
I've had a look at the link and it looks like it adds a floating point calculator but you have to type calc then your calculation. How would I save the values to a valiable such as DIFF in the example of the OP?

Thanks
 
Here is a good list of examples:

http://www.basicallytech.com/blog/index.php?/archives/23-command-line-calculations-using-bc.html

You use the command bc to output calculations with floating points.

a brief introduction to using bc with files

Using bc with files allows complex calculations to be repeated, again and again, a bit like using a spreadsheet to run the same calculations on changing figures ... but faster.

Here is a simple example:

scale=2

/* C-style comments
are allowed, as are spaces */

print "\nConvert Fahrenheit to Celsius\n\n"
print "Temperature in Fahrenheit: " ; fah = read()
print "\n"
print "Equivalent Temperature in Celsius is: "
(fah - 32.0) * 5.0 / 9.0
quit

Create and save the file, then run it like this:

$ bc -q filename

Convert Fahrenheit to Celsius

Temperature in Fahrenheit: 61

Equivalent Temperature in Celsius is: 16.11

Note that this example has only been tested with GNU bc. Other (proprietary) versions of bc may have more stringent syntax requirements. Some bcs don't allow the use of print or read, for example, so you have to edit your file before each calculation. Not very useful.
 
Last edited:
Back
Top Bottom