Home » How to do integer & float calculations, in bash or other languages/frameworks?

How to do integer & float calculations, in bash or other languages/frameworks?

Solutons:


There are lots of options!!!

Summary

$ printf %.10f\n "$((10**9 * 20/7))e-9"   # many shells. Not mksh.
$ echo "$((20.0/7))"                       # (ksh93/zsh/yash, some bash)
$ awk "BEGIN {print (20+5)/2}"
$ zcalc
$ bc <<< 20+5/2
$ bc <<< "scale=4; (20+5)/2"
$ dc <<< "4 k 20 5 + 2 / p"
$ expr 20 + 5
$ calc 2 + 4
$ node -pe 20+5/2  # Uses the power of JavaScript, e.g. : node -pe 20+5/Math.PI
$ echo 20 5 2 / + p | dc 
$ echo 4 k 20 5 2 / + p | dc 
$ perl -E "say 20+5/2"
$ python -c "print(20+5/2)"
$ python -c "print(20+5/2.0)"
$ clisp -x "(+ 2 2)"
$ lua -e "print(20+5/2)"
$ php -r 'echo 20+5/2;'
$ ruby -e 'p 20+5/2'
$ ruby -e 'p 20+5/2.0'
$ guile -c '(display (+ 20 (/ 5 2)))'
$ guile -c '(display (+ 20 (/ 5 2.0)))'
$ slsh -e 'printf("%f",20+5/2)'
$ slsh -e 'printf("%f",20+5/2.0)'
$ tclsh <<< 'puts [expr 20+5/2]'
$ tclsh <<< 'puts [expr 20+5/2.0]'
$ sqlite3 <<< 'select 20+5/2;'
$ sqlite3 <<< 'select 20+5/2.0;'
$ echo 'select 1 + 1;' | sqlite3 
$ psql -tAc 'select 1+1'
$ R -q -e 'print(sd(rnorm(1000)))'
$ r -e 'cat(pi^2, "n")'
$ r -e 'print(sum(1:100))'
$ smjs
$ jspl
$ gs -q  <<< "5 2 div 20 add  ="

Details

Shells

You can use POSIX arithmetic expansion for integer arithmetic echo "$((...))":

$ echo "$((20+5))"
25
$ echo "$((20+5/2))"
22

Quite portable (ash dash yash bash ksh93 lksh zsh):
Using printf ability to print floats we can extend most shells to do floating point math albeit with a limited range (no more than 10 digits):

$ printf %.10f\n "$((1000000000 *   20/7  ))e-9"
2.8571428570

ksh93, yash and zsh do support floats here:

$ echo "$((1.2 / 3))"
0.4

only ksh93 (directly) and zsh loading library mathfunc here:

$ echo "$((4*atan(1)))"
3.14159265358979324

(zsh need to load zmodload zsh/mathfunc to get functions like atan ).


Interactively with zsh:

$ autoload zcalc
$ zcalc
1> PI/2
1.5708
2> cos($1)
6.12323e-17
3> :sci 12
6.12323399574e-17

With (t)csh (integer only):

% @ a=25 / 3; echo $a
8

In the rc shell family, akanga is the one with arithmetic expansion:

; echo $:25/3
8

POSIX toolchest

bc (see below for interactive mode), manual here

Mnemonic: best calculator (though the b is in fact for basic).

$ echo 20+5/2 | bc
22
$ echo 'scale=4;20+5/2' | bc
22.5000

(supports arbitrary precision numbers)


bc interactive mode:

$ bc
bc 1.06.95
Copyright 1991-1994, 1997, 1998, 2000, 2004, 2006 Free Software Foundation, Inc.
This is free software with ABSOLUTELY NO WARRANTY.
For details type `warranty'. 
5+5
10

2.2+3.3
5.5

Rush’s solution, expr (no interactive mode):

$ expr 20 + 5
25
$ expr 20 + 5 / 2
22

Joshua’s solution: awk (no interactive mode):

$ calc() { awk "BEGIN{print $*}"; }
$ calc 1/3
0.333333

Other more or less portable tools

Arcege’s solution, dc (interactive mode: dc):

Which is even more fun since it works by reverse polish notation.

$ echo 20 5 2 / + p | dc 
22
$ echo 4 k 20 5 2 / + p | dc 
22.5000

But not as practical unless you work with reverse polish notation a lot.

Note that dc predates bc and bc has been historically implemented as a wrapper around dc but dc was not standardised by POSIX


DQdims’s calc (required sudo apt-get install apcalc):

$ calc 2 + 4
6

General purpose language interpreters:

manatwork’s solution, node (interactive mode: node; output function not needed):

$ node -pe 20+5/2  # Uses the power of JavaScript, e.g. : node -pe 20+5/Math.PI
22.5

Perl (interactive mode: perl -de 1):

$ perl -E "say 20+5/2"
22.5

Python (interactive mode: python; output function not needed):

$ python -c "print(20+5/2)"
22 # 22.5 with python3
$ python -c "print(20+5/2.0)"
22.5

Also supports arbitrary precision numbers:

$ python -c 'print(2**1234)'
295811224608098629060044695716103590786339687135372992239556207050657350796238924261053837248378050186443647759070955993120820899330381760937027212482840944941362110665443775183495726811929203861182015218323892077355983393191208928867652655993602487903113708549402668624521100611794270340232766099317098048887493809023127398253860618772619035009883272941129544640111837184

If you have clisp installed, you can also use polish notation:

$ clisp -x "(+ 2 2)"

Marco’s solution, lua (interactive mode: lua):

$ lua -e "print(20+5/2)"
22.5

PHP (interactive mode: php -a):

$ php -r 'echo 20+5/2;'
22.5

Ruby (interactive mode: irb; output function not needed):

$ ruby -e 'p 20+5/2'
22
$ ruby -e 'p 20+5/2.0'
22.5

Guile (interactive mode: guile):

$ guile -c '(display (+ 20 (/ 5 2)))'
45/2
$ guile -c '(display (+ 20 (/ 5 2.0)))'
22.5

S-Lang (interactive mode: slsh; output function not needed, just a ; terminator):

$ slsh -e 'printf("%f",20+5/2)'
22.000000
$ slsh -e 'printf("%f",20+5/2.0)'
22.500000

Tcl (interactive mode: tclsh; output function not needed, but expr is):

$ tclsh <<< 'puts [expr 20+5/2]'
22
$ tclsh <<< 'puts [expr 20+5/2.0]'
22.5

Javascript shells:

$ smjs
js> 25/3
8.333333333333334
js>

$ jspl
JSC: 25/3

RP: 8.33333333333333
RJS: [object Number]
JSC:
Good bye...

$ node
> 25/3
8.333333333333334
>

Various SQL’s:

SQLite (interactive mode: sqlite3):

$ sqlite3 <<< 'select 20+5/2;'
22
$ sqlite3 <<< 'select 20+5/2.0;'
22.5

MySQL:

mysql -BNe 'select 1+1'

PostgreSQL:

psql -tAc 'select 1+1

_The options on mysql and postgres stop the ‘ascii art’ image !

Specialised math-oriented languages:

R in plain mode – lets generate 1000 Normal random numbers and get the standard deviation and print it

$ R -q -e 'print(sd(rnorm(1000)))'
> print(sd(rnorm(1000)))
[1] 1.031997

R using the littler script – lets print pi squared

$ r -e 'cat(pi^2, "n")'
9.869604
$  r -e 'print(sum(1:100))'
[1] 5050

PARI/GP, an extensive computer algebra system for number theory, linear algebra, and many other things

$ echo "prime(1000)"|gp -q
7919                        // the 1000th prime
$ echo "factor(1000)" | gp -q
[2 3]
[5 3]                       // 2^3*5^3
$ echo "sum(x=1,5,x)" | gp -q
15                          // 1+2+3+4+5

GNU Octave (a high-level interpreted language, primarily intended for numerical computations)

Also supports complex numbers:

$ octave
>> 1.2 / 7
ans =  0.17143
>> sqrt(-1)
ans =  0 + 1i

Julia, high-performance language and interpreter for scientific and numerical computing.

Non-interactive option:

$ julia -E '2.5+3.7'
6.2

GhostScript
GhostScript is a PostScript interpreter, very commonly installed even in very old distributions.
See PostScript docs for a list of supported math commands.

Interactive example:

$ GS_DEVICE=display gs
GPL Ghostscript 9.07 (2013-02-14)
Copyright (C) 2012 Artifex Software, Inc.  All rights reserved.
This software comes with NO WARRANTY: see the file PUBLIC for details.
GS>5 2 div 20 add  =
22.5
GS>

There are many ways to calculate.
For simple expressions you can use bash itself:

echo $((20+5))

or expr:

expr 20 + 5

And for complex cases there is great tool bc:

echo "20+5" | bc

Btw, bc can calculate even very complex expression with roots, logarithms, cos, sin and so on.

Nobody has mentioned awk yet?

Using POSIX shell functions, and awk math power, just define this (one line) function:

calc(){ awk "BEGIN { print $*}"; }

Then just execute things like calc 1+1 or calc 5/2

Note: To make the function always available, add it to ~/.bashrc (or your corresponding shell’s startup file)

Of course, a little script named “calc” with the following contents:

#!/bin/sh -
awk "BEGIN { print $* }"

could also work.

Related Solutions

Extract file from docker image?

You can extract files from an image with the following commands: docker create $image # returns container ID docker cp $container_id:$source_path $destination_path docker rm $container_id According to the docker create documentation, this doesn't run the...

Transfer files using scp: permission denied

Your commands are trying to put the new Document to the root (/) of your machine. What you want to do is to transfer them to your home directory (since you have no permissions to write to /). If path to your home is something like /home/erez try the following:...

What’s the purpose of DH Parameters?

What exactly is the purpose of these DH Parameters? These parameters define how OpenSSL performs the Diffie-Hellman (DH) key-exchange. As you stated correctly they include a field prime p and a generator g. The purpose of the availability to customize these...

How to rsync multiple source folders

You can pass multiple source arguments. rsync -a /etc/fstab /home/user/download bkp This creates bkp/fstab and bkp/download, like the separate commands you gave. It may be desirable to preserve the source structure instead. To do this, use / as the source and...

Benefits of Structured Logging vs basic logging

There are two fundamental advances with the structured approach that can't be emulated using text logs without (sometimes extreme levels of) additional effort. Event Types When you write two events with log4net like: log.Debug("Disk quota {0} exceeded by user...

Interfaces vs Types in TypeScript

2019 Update The current answers and the official documentation are outdated. And for those new to TypeScript, the terminology used isn't clear without examples. Below is a list of up-to-date differences. 1. Objects / Functions Both can be used to describe the...

Get total as you type with added column (append) using jQuery

One issue if that the newly-added column id's are missing the id number. If you look at the id, it only shows "price-", when it should probably be "price-2-1", since the original ones are "price-1", and the original ones should probably be something like...

Determining if a file is a hard link or symbolic link?

Jim's answer explains how to test for a symlink: by using test's -L test. But testing for a "hard link" is, well, strictly speaking not what you want. Hard links work because of how Unix handles files: each file is represented by a single inode. Then a single...

How to restrict a Google search to results of a specific language?

You can do that using the advanced search options: http://www.googleguide.com/sharpening_queries.html I also found this, which might work for you: http://www.searchenginejournal.com/how-to-see-google-search-results-for-other-locations/25203/ Just wanted to add...

Random map generation

Among the many other related questions on the site, there's an often linked article for map generation: Polygonal Map Generation for Games you can glean some good strategies from that article, but it can't really be used as is. While not a tutorial, there's an...

How to prettyprint a JSON file?

The json module already implements some basic pretty printing in the dump and dumps functions, with the indent parameter that specifies how many spaces to indent by: >>> import json >>> >>> your_json = '["foo", {"bar":["baz", null,...

How can I avoid the battery charging when connected via USB?

I have an Android 4.0.3 phone without root access so can't test any of this but let me point you to /sys/class/power_supply/battery/ which gives some info/control over charging issues. In particular there is charging_enabled which gives the current state (0 not...

How to transform given dataset in python? [closed]

From your expected result, it appears that each "group" is based on contiguous id values. For this, you can use the compare-cumsum-groupby pattern, and then use agg to get the min and max values. # Sample data. df = pd.DataFrame( {'id': [1, 2, 2, 2, 2, 2, 1, 1,...

Output of the following C++ Program [closed]

It works exactly like this non-recursive translation: int func_0() { return 2; } int func_1() { return 3; } int func_2() { return func_1() + func_0(); } // Returns 3 + 2 = 5 int func_3() { return func_2() + func_1(); } // Returns 5 + 3 = 8 int func_4() { return...

Making a circle out of . (periods) [closed]

Here's the maths and even an example program in C: http://pixwiki.bafsoft.com/mags/5/articles/circle/sincos.htm (link no longer exists). And position: absolute, left and top will let you draw: http://www.w3.org/TR/CSS2/visuren.html#choose-position Any further...

Should I use a code converter (Python to C++)?

Generally it's an awful way to write code, and does not guarantee that it will be any faster. Things which are simple and fast in one language can be complex and slow in another. You're better off either learning how to write fast Python code or learning C++...

tkinter: cannot concatenate ‘str’ and ‘float’ objects

This one line is more than enough to cause the problem: text="რეგულარი >> "+2.23+ 'GEL' 2.23 is a floating-point value; 'GEL' is a string. What does it mean to add an arithmetic value and a string of letters? If you want the string label 'რეგულარი...