Friday, October 28, 2011

Floating point arithmetics in Bash

Bash does not support floating point arithmetics. However, doing floating point operations (using real numbers instead of integers) may be easily done in Bash using external programs. The following script shows how to do real and integer operations in Bash script using the bc program for the operation on real numbers and the internal Bash command for the integer operation.

#!/bin/bash

total=10
index=0

while [ "$index" -lt "$total" ]
do

 a=$index
 b=$(echo "$a+0.5" | bc)
 ((c=a+1))

 echo $a $b $c

 ((index++))
done

In the above script a variable a is always an integer number. The command
b=$(echo "$a+0.5" | bc)
assigns to a variable b value of a+0.5 sending the expression to the bc program. The next command
((c=a+1))
uses the internal Bash command to add two integer numbers (c = a + 1). The result of the above script is:
0 .5 1
1 1.5 2
2 2.5 3
3 3.5 4
4 4.5 5
5 5.5 6
6 6.5 7
7 7.5 8
8 8.5 9
9 9.5 10
bc program allows you to do all basic operations on real numbers. Read the bc manual
man bc
to see the list of available commands. Remember that the bc program command has to be included in quotation.

No comments:

Post a Comment