linux poison RSS
linux poison Email

Bash Script: Performing Floating point Math Operation

NOTE: If your program depends heavily on Math operation (floating point), better switch to ksh instead of traditional bash.

Bash does not support floating point operations but it's possible to redirects these Math operation to some other program (bc).

The "bc" calculator comes as a part of your Linux distro, so there's no need for you to install anything extra. In addition to performing simple math functions, it can also perform conversions between different number systems, perform a number of scientific math functions, and can even run programs that you write and save in a text file. look the bc man pages for more details.

Below is simple bash script which demonstrate the usage of bc commands in the script

Source: cat floating.sh
#!/bin/bash

echo "----- Addition ------"
x=10.2
y=20.2
z=`echo $x+$y|bc`
echo $z
echo "------ Division -----"
x=3
y=25
z=`echo $y/$x|bc`
echo $z

echo "----- Substration -----"
x=20.9
y=33.67
z=`echo $y-$x|bc`
echo $z

echo "----- Multiply -----"
x=2.23
y=4.44
z=`echo $x*$y|bc`
echo $z

echo "----- Square root -----"
x=215
z=`echo "scale=4;sqrt($x)" | bc -l`
echo $z

echo "----- Powers of -----"
x=4.2
y=2
z=`echo $x^$y | bc -l`
echo $z

Output: /floating.sh
----- Addition ------
30.4
------ Division -----
8
----- Substration -----
12.77
----- Multiply -----
9.90
----- Square root -----
14.6628
----- Powers of -----
17.64





0 comments:

Post a Comment

Related Posts with Thumbnails