Floating Point Arithmetic in Linux Bash Scripts

Floating Point Arithmetic in Linux Bash Scripts

Unlock the power of precise calculations in Linux Bash scripts with floating point math Discover how to overcome the limitations of integer-only support and harness tools like bc and the standard math library Enhance your scripting capabilities and achieve accurate results effortlessly

Some Noticeable Information

The Linux Bash shell only supports integer arithmetic and cannot perform calculations on floating point numbers.

The bc utility in Linux enables interactive and shell script-based precision floating point calculations. With bc, it is possible to specify the number of decimal places for display and conduct calculations with arbitrary precision, incorporating functions from the standard math library.

The Linux Bash shell is restricted to performing integer arithmetic exclusively, lacking the ability to comprehend or handle floating-point calculations. To overcome this limitation, the bc utility facilitates precise floating-point calculations both interactively and within shell scripts.

Why Bash Only Supports Integers

The original decision to limit the Unix Bourne shell to integer arithmetic may have been influenced by the early use of a single byte of RAM to represent an integer. The reasons behind this decision are unknown. Similarly, the Bash shell, which is a version of the Bourne shell in Linux, also adopted the restriction.

Bash itself is unable to carry out calculations involving floating point numbers. Additionally, when performing calculations on integers that would result in a fractional value, the answer is truncated and reported as an integer. This applies to both command line operations and Bash shell scripts. Depending on your specific use case, this limitation could be problematic or even prevent progress.

Linux offers two utility applications for performing floating point calculations: dc and bc. While dc operates using reverse-Polish notation, making it somewhat unique, bc is a versatile tool that can be used interactively or as a command. In this discussion, we will focus on bc.

The Problem

Let’s get Bash to divide six by three.

echo $((6 / 3))

Floating Point Arithmetic in Linux Bash Scripts

We get our expected answer of two. Now let’s divide six by seven. Clearly, that will have a fractional answer.

echo $((6 / 7))

Floating Point Arithmetic in Linux Bash Scripts

Zero is obviously wrong. Let’s try again, dividing 16 by 7.

echo $((16 / 7))

Floating Point Arithmetic in Linux Bash Scripts

The result obtained is two. The reason for this is that the decimal part of the answer is being disregarded, leading to truncation of the answer. In the initial example, there was no decimal part, resulting in the accurate answer.

In the second example, the answer only consists of a fractional part, resulting in a zero value when the fractional part is removed.

In the third example, when dividing 7 into 16, there are two whole divisions with a remaining fractional part. Again, the fractional part is disregarded and the result is truncated.

Using bc Interactively

You can use bc as an interactive calculator by typing bc and pressing the “Enter” key.

bc

Floating Point Arithmetic in Linux Bash Scripts

When the bc application is launched, it will announce its version number and wait for your input. Enter a calculation and press "Enter" to have bc evaluate it and show the result.

2688.5

Floating Point Arithmetic in Linux Bash Scripts

You can use “Ctrl+L” to clear the screen, and “Ctrl+D” to exit from the program. Let’s try a calculation that will have a fractional component in the answer.

22 / 7

Floating Point Arithmetic in Linux Bash Scripts

The

The actual outcome is not what we anticipated. Surprisingly, despite the capability of utilizing arbitrary precision, bc does not display the decimal point or any subsequent digits by default.

In order to reveal the accurate result, we must specify the number of decimal places to be shown to bc. This can be achieved by utilizing the "scale" command. Let's request for the display of seven decimal places and recalculate our computation.

scale=722 / 7

Floating Point Arithmetic in Linux Bash Scripts

The "scale" setting remains unchanged after this calculation: scale=100.300003 * 0.5. The number of decimal places set determines the maximum number of decimal places displayed by bc. If the result does not require that many decimal places, it is shown with the exact number of decimal places needed, without any unnecessary zeros.

Floating Point Arithmetic in Linux Bash Scripts

To display multiple calculations on the same line, you can separate them using a semicolon ";". The answers will be shown on individual lines in the order they were listed.

25 * 6; 12.5 + 45.001; 3 + 5 + 7 + 9

Floating Point Arithmetic in Linux Bash Scripts

You can include the “scale” command in the list, too.

scale=8; 22 / 7; scale=3; 0.3 * 0.071

Floating Point Arithmetic in Linux Bash Scripts

The Standard Math Library

The -l (standard math library) option causes bc to load a set of functions, and sets “scale” to 20 decimal places.

bc -l22 / 7

Floating Point Arithmetic in Linux Bash Scripts

With the standard library loaded, you can use these functions in your calculations.

s (x): The sine of x

c (x): The cosine of x.

a (x): The arctangent of x

l (x): The natural logarithm of x

e (x): The exponential of e to the value x

j (n,x): The Bessel function of integer order n of x.

Sine, cosine, and arctangent use radian values.

s (1.1) c (.891207) a (.628473)

Floating Point Arithmetic in Linux Bash Scripts

Sending Input to bc on the Command Line

Redirect and pipe input to bc to process and display the output in the terminal window. You have the option to redirect into bc with or without the -l (standard math library) option.

bc <<< 22/7bc -l <<< 22/7

Floating Point Arithmetic in Linux Bash Scripts

To pipe input to bc, the input has to be the output of another process. It’s convenient to use echo for this.

echo 22/7 | bcecho 22/7 | bc -l

Floating Point Arithmetic in Linux Bash Scripts

If you have spaces in your input, or want to include the “scale” command, wrap your input in quotation marks.

echo "22 / 7" | bc -lecho "scale=6; 22 / 7" | bc

Floating Point Arithmetic in Linux Bash Scripts

Using bc in Bash Shell Scripts

Now, with all the necessary components, we can efficiently execute floating point calculations in our bash scripts, ensuring the desired level of precision. Furthermore, it is possible to incorporate Bash variables, including script parameters, into our calculations.

Please copy the following content into an editor and save it as "pi.sh". After that, you can close the editor.

#!/bin/bash

first_number=22

second_number=7

pi=$(echo "scale=$1; $first_number/$second_number" | bc)

echo "Pi to $1 decimal places is: $pi"

We utilize the variables "first_number" and "second_number" to store two numeric values. These variables are employed in the input that is being directed into bc.

Furthermore, we have assigned the first command line parameter passed to the script, "$1", as the value to assign to "scale".

Before we can try our script, we need to make it executable with chmod.

chmod +x pi.sh

Floating Point Arithmetic in Linux Bash Scripts

Let’s try our script with different command line values.

/pi.sh 5./pi.sh 14./pi.sh 20

Floating Point Arithmetic in Linux Bash Scripts

We get pi displayed to number of places we specify on the command line to our script.

It All Adds Up

Enhancing our scripts with accurate calculations extends beyond the constraints of Bash's integer-only mathematics. Although echo's utilization for piping input to bc within scripts may appear somewhat cumbersome, its effectiveness surpasses any inconveniences.

Editor's P/S

As a Gen Z netizen, I find the limitations of integer-only arithmetic in the Linux Bash shell to be frustrating. In today's world, where we rely on precise calculations for everything from financial analysis to scientific research, it seems outdated to have a shell that can't handle floating-point numbers.

The bc utility is a helpful workaround, but it's not always the most convenient solution. It would be much better if the Bash shell itself supported floating-point arithmetic natively. This would make it easier to perform complex calculations without having to resort to external tools.

Overall, I think the lack of floating-point support in the Bash shell is a significant limitation that needs to be addressed. I hope that in the future, the shell will be updated to include this essential feature.