FUNDAMENTALS A Complete Guide for Beginners
The division operator ( “/” ) can easily divide two integer numbers in Bash. However, the division of floating point numbers is not as straightforward as integers. To perform floating point division in Bash, users need to rely on some external tools and commands. In this article, I will discuss some of those tools. In addition, I will show how to use them to divide float numbers and shape the result in a desired form.
Commands to Perform Floating Point Division in Bash
There are multiple tools and commands for floating point division. These are bc, dc, awk etc. Furthermore, Python and Perl code can be executed in Bash Shell to perform the division of floating point numbers. Examples illustrating these tools are listed below:
1. “bc” Command
The bc command is the default choice for floating point calculation in Bash. To divide two floating point numbers using bc, use the following syntax:
echo "scale=<precision>; $x / $y" | bc
More about this command will be discussed later in this article.
2. “dc” command
To divide two floating point numbers using the dc command first provide the numbers. Then define the operator. The basic syntax is as follows:
echo "$x $y / p" | dc
Replace the variables with the numerator and the denominator of the division respectively. For example, consider a division of 5.5 by 2.3:
echo "5.5 2.3 / p" | dc
The command prints 2 as the result of the division. Because the default precision is set to zero. However, you can change the precision by defining it before the numbers:
echo 4 k 5.5 2.3 / p | dc
4 k
indicates that the result should be printed up to four decimal places. Once executed the command prints the result of the division 2.3913 in the terminal.
3. “awk” Command
The awk command with its BEGIN block can calculate the result of floating point division. The basic syntax is given below:
awk "BEGIN {print $x / $y}"
Replace the variables x and y with the numbers of your division. For example:
awk "BEGIN {print 5.5 / 2.3}"
Here I perform the division of 5.5 by 2.3. The result of the division is 2.3913. By default, awk prints the result up to four decimal places.
4. “python2/python3” Command
Bash users can execute Python code in Bash shell using python2 or python3 commands. To divide two floating point numbers using Python version 3, use the syntax below:
python3 -c "print($x / $y)"
The -c
flag specifies a Python command to be executed in the Bash shell. Replace the variables x
and y
with the divisor and dividend. For instance:
python3 -c "print(5.5 / 2.3)"
Python provides a very precise result of the division. There are almost 16 digits after the decimal point.
Note: If Python is not installed in your system, install it using the following command:
sudo apt-get install python3
5. “perl” Command
Perl is a popular programming language. Bash users can use Perl code to divide floating point numbers in Bash. The syntax is given below:
perl -e 'print $x / $y, "\n";'
Command flag -e
indicates a Perl code to be executed. "\n"
tells Bash to print the result in a new line. Now as an example, divide the float 5.5 by another floating point number 2.3:
perl -e 'print 5.5 / 2.3, "\n";'
Like Python, Perl provides the result of floating point division with considerable precision. Moreover, you can format the output to get the desired precision by utilizing the printf command. Look at the code below which is written to format the output up to six decimal places:
perl -e "$x=5.5; $y=2.3; printf("%.6f\n", $x/$y)'
Here, "%.6f\n"
indicates that the result should contain six digits after the decimal point. See the image, the result is 2.391304, with 6 digits (391304) after the decimal point.
Division of Two Floating Point Numbers in Bash
To divide a floating point number by another using the bc command, first, write the expression using the echo command. After that, pipe that expression for evaluation to bc. Here is how you can do that:
#!/bin/bash
res=$(echo "6.28 / 3.14" | bc)
echo "Result: $res"
String "6.24 / 3.14"
is passed to bc using a pipe operator. After that, bc evaluates the division which is then stored in the res variable.
An important thing to notice here- the numerator and the denominator of this division are craftly chosen. Though the divisor and dividend are floating point numbers, the result of the division is an integer. Therefore, the result is accurate even without setting any precision value.
Division of Floats up to Desired Precision in Bash
Not all floating point division results in a whole number. For instance, 10.5 divided by 3.14 has a fractional part in its result. But when you perform such divisions using the bc tool without setting the precision value, you will get the integer portion of the result only. Look at the following division:
echo "10.5 / 3.14" | bc
See from the output image, 3 is printed as the result of 10.5 divided by 3.14. But the actual result should be 3.34…
To get the result of a division up to the desired precision set a scale value and parse it to bc:
#!/bin/bash
res=$(echo "scale=2 10.5 / 3.14" | bc)
echo "Result: $res"
Here, scale=2
determines the precision up to 2 decimal places. Therefore 3.34 is shown as the result of the division.
Division of User-Inputted Floating Point Variables
Think about a situation when the numerator and denominator of a division come from user input. So it is crucial to handle user-inputted floating-point variables. The following script takes two numbers from the user and divides one by another. The numbers can be either floating point or integer:
#!/bin/bash
read -p "Enter the numerator: " numerator
read -p "Enter the denominator: " denominator
res=$(echo "scale=4; $numerator / $denominator" | bc)
echo "Result of Division: $res"
This Bash script prompts the user to input a numerator and a denominator. It utilizes the read command to prompt users for the inputs. Then it uses the echo command with the bc tool to perform the division with the precision of four decimal places using scale=4
. The result is stored in the res variable and displayed in the terminal.
Handling Floating-Point Result of an Integer Division
Arithmetic expansion can only perform the division of two integer numbers. However, a division of integers can yield a floating point. For instance, 10 divided by 3 is 3.33… Though 10 and 3 are integers, the result of 10 by 3 is a float. In such division cases, arithmetic expansion provides the integer part of the result only. For overcoming this limitation the printf command is useful.
The printf command with the necessary format specifier is capable of capturing the result of a division up to a certain precision. The general syntax is:
printf "%.<precision>f\n" $((10**<precision> * <numerator>/<denominator>))e-<precision>
To make this code work, replace <numerator>
, <denominator>
, and <precision>
with their corresponding values. For instance, the following code can capture the result of 10 by 3 up to three decimal places:
#!/bin/bash
res=$(printf "%.3f\n" $((10**3*10/3))e-3)
echo "Result of Division: $res"
Code part $((10**3*10/3))
performs arithmetic expansion. First, 10 raised to the power of 3 is 1000. Then 1000 is multiplied by 10, yielding 10000. Finally, 10000 is divided by 3, resulting in 3333.
In $((10**3*10/3))e-3
, the result of arithmetic expansion is multiplied by e-3. Where e-3 represents multiplying the preceding value by 10 to the power of -3. In this case, it means dividing the preceding value by 1000. So, 3333e-3 is equivalent to 3.333.
Finally, the printf "%.3f\n"
statement specifies a format for printing. Where, %.3f
specifies that the number should be formatted as a floating point with three decimal places.
Conclusion
In conclusion, the division of float numbers in Bash is a simple task. Nonetheless, it requires some familiarity with the tools and commands that support floating point arithmetic. This article tries to give you a glimpse of those commands. I believe from now on you can easily divide two floating point numbers in Bash.
People Also Ask
Can bash do floating-point arithmetic without using an external command?
Technically Yes. But you need to perform some low-level bitwise calculations to achieve that. The use of external tools and commands to do so is a more practical approach.
Can I ensure half-rounding in the result of a division in Bash?
Yes, you can do it natively in Bash using a math trick. Let’s say you are dividing x by y. Instead of x/y
you can write the division as (x+y/2)/y
. This ensures an additional 0.5 with the result so that Bash automatically rounds it to the nearest halfway. For instance, 3/2 is 1.5. Without halfway rounding the result of this division is 1. But when you write the division as (3+2/2)/2) the result will be two.
Does ksh support floating point calculation?
Yes, the Korn shell or ksh supports floating point calculation. You can work with all the mathematical functions of libraries such as libm
while using ksh.
How to tell Bash to consider the result of an integer division as float?
To tell Bash to consider the result of an integer division as float, you have to take a tortuous path. Because Bash can recognize integer numbers only not floats. The following script can tell Bash to consider the result of an integer division as a floating point number:
divide() # Arguments: numerator and denominator
{
if [ $2 -eq 0 ]; then
echo "Division by 0"
return 1
fi
local precision=12
local count=${count:-0}
local decimal_point=.
local quotient=$(($1 / $2))
echo -n $quotient
local product=$(($quotient * $2))
if [ $count -eq 0 ] && [ $product -ne $1 ]; then
echo -n $decimal_point
fi
if [ $1 -eq $product ] || [ $count -eq $precision ]; then
echo return
fi
local remainder=$(($1 - $product))
count=$(($count + 1))
divide $(($remainder * 10)) $2
}
# Example usage:
dividend=22
divisor=7
divide $dividend $divisor
What is the default scale value of “bc“?
The default scale value of bc is typically set to 0. More accurately the default scale value of bc is the maximum scale of the expressions involved unless otherwise mentioned.
Related Articles
- Performing Math Operations in Bash [12+ Commands Explained]
- How to Calculate in Bash [3 Practical Examples]
- How to Sum Up Numbers in Bash [Explained With Examples]
- How to Divide Two Numbers in Bash [8 Easy Ways]
- How to Use “Mod” Operator in Bash [5 Basic Usage]
- How to Format Number in Bash [6 Cases]
- How to Generate Random Number in Bash [7 Easy Ways]
- How to Convert Hexadecimal Number to Decimal in Bash
- [Solved] “binary operator expected” Error in Bash
- [Fixed] “integer expression expected” Error in Bash
<< Go Back to Arithmetic Operators in Bash | Bash Operator | Bash Scripting Tutorial