How to Do Floating Point Math in Linux Bash Scripts

Trending 1 month ago

Key Takeaways

  • The Linux Bash ammunition only supports integer arithmetic and cannot execute calculations connected floating constituent numbers.
  • The bc inferior successful Linux allows for precision floating constituent calculations interactively and successful ammunition scripts.
  • Using bc, you tin group nan number of decimal places to show and execute calculations pinch arbitrary precision, including utilizing functions from nan modular mathematics library.

The Linux Bash ammunition supports integer arithmetic only. It tin neither understand nor header pinch floating constituent calculations. The bc inferior gives you precision floating constituent calculations interactively and successful ammunition scripts.

Why Bash Only Supports Integers

The original creation determination to restrict nan Unix Bourne shell to integer arithmetic might beryllium rooted successful nan early-computing mapping of an integer to a azygous byte of RAM. We whitethorn ne'er cognize what was genuinely down nan decision. Nor, for that matter, why nan Linux type of nan Bourne shell, nan Bash shell, chose to travel suit.

On its own, Bash cannot execute calculations connected floating constituent numbers, and calculations connected integers that would person a fractional portion to nan answer, are reported arsenic truncated integer values. This is existent connected nan bid statement and successful Bash ammunition scripts. Depending connected your usage case, this tin beryllium problematic aliases show-stopping.

Linux comes pinch 2 inferior applications that let you to execute floating constituent calculations. One of these is dc. It’s a spot of a curio, operating arsenic it does successful reverse-Polish notation. The different instrumentality is bc. It tin beryllium utilized interactively aliases arsenic a command, and it’s nan solution we’ll talk here.

The Problem

Let’s get Bash to disagreement six by three.

echo $((6 / 3))
Dividing 2 integers pinch nary remainder connected nan Bash bid line

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

echo $((6 / 7))
Dividing 2 integers connected nan Bash bid statement pinch a fractional remainder. The remainder is ne'er shown.

Zero is evidently wrong. Let’s effort again, dividing 16 by 7.

echo $((16 / 7))
Illustraing nan rumor pinch BAsh only supporting integer arithmetic by dividing 2 integers. The fractional remainder is discarded.

We get an reply of two. What’s happening is nan fractional portion of nan reply is being discarded, truthful nan reply is truncated. There was nary fractional portion successful nan first example, truthful we get nan correct answer.

The 2nd illustration had nary integer constituent successful nan answer, only a fractional part. Because nan fractional portion has been discarded nan reply we’re shown is zero.

In nan 3rd example, 7 divides into 16 twice, pinch a fractional remainder. Again, nan remainder is discarded, and nan consequence is truncated.

Using bc Interactively

You tin usage bc arsenic an interactive calculator by typing bc and pressing nan “Enter” key.

The bc invited connection and prompt

The bc exertion launches, announces its type number, and past waits for your input. Typing a calculation and pressing “Enter” causes bc to measure nan calculation and show nan answer.

16 * 4

1024 / 32

2^2 * 1024

Three illustration calculations successful bc, successful interactive mode

You tin usage “Ctrl+L” to clear nan screen, and “Ctrl+D” to exit from nan program. Let’s effort a calculation that will person a fractional constituent successful nan answer.

22 / 7
bc defaults to showing nary decimal places. Pi is truncated to 3.

That’s not what we expected. Counterintuitively, though bc allows america to usage arbitrary precision, by default it won’t show nan decimal constituent nor immoderate figures that travel it.

To make nan existent reply visible we request to show bc really galore decimal places to display. We do this pinch nan “scale” command. We’ll inquire for 7 decimal places, and re-do our calculation.

22 / 7
Using standard to show bc to show up to 7 decimal places successful nan results of calculations

Finally, we’re getting somewhere. The “scale” mounting remains successful spot until you alteration it. Setting nan number of decimal places tells bc nan maximum number of places to display. If an reply doesn’t request that galore decimal places, it’s displayed pinch nan number of decimal places it requires and nary more. It doesn’t get padded pinch meaningless zeroes.

0.300003 * 0.5
bc only displays nan decimal places it needs. Setting standard to 10 will not unit 10 decimal places to beryllium used. If an reply requires less decimal places, they're nan only ones that are displayted.

You tin database different calculations connected nan aforesaid statement by utilizing a semicolon “;” to abstracted them. The answers are displayed connected per statement arsenic usual, successful nan bid nan calculations were listed.

25 * 6; 12.5 + 45.001; 3 + 5 + 7 + 9
You tin adhd aggregate calculation to a statement by separating them pinch semi-colons.

You tin see nan “scale” bid successful nan list, too.

scale=8; 22 / 7; scale=3; 0.3 * 0.071
You tin alteration nan mounting of standard for each calculation, moreover calculations connected nan aforesaid bid line

The Standard Math Library

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

bc -l
22 / 7
bc launched pinch nan -l option, showing pi calculated to 20 decimal places

With nan modular room loaded, you tin usage these functions successful your calculations.

  • s (x): The sine of x
  • c (x): The cosine of x.
  • a (x): The arctangent of x
  • l (x): The earthy logarithm of x
  • e (x): The exponential of e to nan worth x
  • j (n,x): The Bessel usability of integer bid n of x.

Sine, cosine, and arctangent usage radian values.

s (1.1)
c (.891207)
a (.628473)
Calculating nan sine, cosine, and arctan successful bc successful interactive mode

Sending Input to bc connected nan Command Line

You tin usage redirection and pipes to nonstop input to bc. It processes your input and displays nan reply successful nan terminal window.

You tin redirect into bc pinch aliases without nan -l (standard mathematics library) option.

bc <<< 22/7
bc -l <<< 22/7
Redirecting input into bc and bc -l

To tube input to bc, nan input has to beryllium nan output of different process. It’s convenient to usage echo for this.

echo 22/7 | bc
echo 22/7 | bc -l
Using echo to tube input into bc and bc -l

If you person spaces successful your input, aliases want to see nan “scale” command, wrap your input successful quotation marks.

echo "22 / 7" | bc -l
echo "scale=6; 22 / 7" | bc
Wrapping input that includes spaces successful quotation marks to tube it into bc and bc -l

Using bc successful Bash Shell Scripts

We’ve now sewage each we request to beryllium capable to execute floating constituent calculations successful our bash scripts, to our chosen precision. We tin besides reference Bash variables successful our calculations, including parameters to nan script.

Here’s our illustration script. Copy this matter into an editor, prevention it arsenic “”, past adjacent your editor.



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

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

We usage 2 variables, “first_number” and “second_number” to clasp 2 numerical values. We usage those variables successful nan input that we’re piping into bc.

We’ve besides utilized nan first bid statement parameter passed to nan script, “$1”, arsenic nan worth to group “scale” to.

Before we tin effort our script, we request to make it executable pinch chmod.

chmod +x
Using chmod to make a book executable

Let’s effort our book pinch different bid statement values.

./ 5
./ 14
./ 20
Output from nan book showing pi calculated to 3 different precisions

We get pi displayed to number of places we specify connected nan bid statement to our script.

It All Adds Up

Moving beyond nan limitations of Bash’s integer-only mathematics gives our scripts precision and accuracy.

Using echo to tube input to bc wrong scripts is simply a small clunky, but it useful perfectly well, and nan benefits are worthy it.

Source Tutorials