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

Using echo "20+5" essentially generates the message "20+5".

What command can I make use of to get the numerical amount, 25 in this instance?

Additionally, what is the most convenient means to do it simply making use of celebration for floating point? As an example, echo $((3224/3807.0)) prints 0: (.

I am seeking solutions making use of either the standard command shell (' command line') itself or via making use of languages that are readily available from the command line.

391
2022-06-07 14:37:02
Source Share
Answers: 13

I make use of a little python manuscript that will certainly review a python expression and also publish the outcome, after that I can run something like

$ pc '[i ** 2 for i in range(10)]'
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

the manuscript is:

#!/usr/local/bin/python3

import sys
import traceback
from codeop import CommandCompiler

compile = CommandCompiler()
filename = "<input>"
source = ' '.join(sys.argv[1:]) + '\n'

try:
    code = compile(source, filename) 
except (OverflowError, SyntaxError, ValueError):
    type, value, sys.last_traceback = sys.exc_info()
    sys.last_type = type
    sys.last_value = value
    if filename and type is SyntaxError:
        # Work hard to stuff the correct filename in the exception
        try:
            msg, (dummy_filename, lineno, offset, line) = value.args
        except ValueError:
            # Not the format we expect; leave it alone
            pass
        else:
            # Stuff in the right filename
            value = SyntaxError(msg, (filename, lineno, offset, line))
            sys.last_value = value
    lines = traceback.format_exception_only(type, value)
    print(''.join(lines))
else:
    if code:
        exec(code)
    else:
        print('incomplete')

Unfortunately I do not bear in mind where I obtained a lot of the code from, so I can not mention it.

6
2022-06-07 16:12:21
Source

There are several means to compute. For straightforward expressions you can make use of bash itself:

echo $((20+5))

or expr:

expr 20 + 5

And for intricate instances there is wonderful device bc:

echo "20+5" | bc

Btw, bc can compute also really intricate expression with origins, logarithms, cos, wrong and more.

44
2022-06-07 15:12:27
Source

You can make use of calc:

If you simply enter calc without various other debates it gets in an interactive setting where you can simply maintain doing mathematics. You exit this by keying exit:

C-style arbitrary precision calculator (version 2.12.3.3)
Calc is open software. For license details type:  help copyright
[Type "exit" to exit, or "help" for help.]

; 2+4
6
; 3+5
8
; 3.4+5
8.4
; 2^4
16
; exit

Or you utilize it with the expression as an argument and also it will certainly give the solution and afterwards exit

$calc 2 + 4
    6
$

calc resembles bc, I similar to the means it act as default much better

20
2022-06-07 15:12:10
Source

For console estimations, I make use of concalc. (sudo aptitude install concalc)

After that, simply type concalc and also hit enter. It will not provide a punctual, yet simply key in the your estimation (no rooms) and also struck enter, and also on the next line, it'll offer you the numerical value.

6
2022-06-07 15:11:58
Source

I such as to discharge up Python and also utilize it as an interactive calculator (however, I'm a Python designer).

13
2022-06-07 15:11:51
Source

I can not think to read "the power of JavaScript" (yet I needed to upvote the solution for the various other components, other than perl certainly.

Almost, for the straightforward instances where integer arithmetic suffices, I make use of the buildin $ (( )) and also advise it. Else, in mostly all instances resemble " "|bc suffices.

For some arithmetic procedures like data, matrix procedures and also even more R is the far better device:

echo 25 + 5 | R --vanilla

and also for tiny datasets and also visual throw out outcomes, oocalc is a wonderful energy.

6
2022-06-07 15:11:20
Source
$> ghc -e '20 + 5'
25
it :: Integer

Also ghci, that is the Glasgow-Haskell Compiler in interactive setting (ghc --interactive, in contrast to it reviewing an expression with -e), creates a remarkable "calculator":

$>ghci
GHCi, version 7.8.3: http://www.haskell.org/ghc/  :? for help
Loading package ghc-prim ... linking ... done.
Loading package integer-gmp ... linking ... done.
Loading package base ... linking ... done.
Prelude> pi
3.141592653589793
Prelude> ceiling pi
4
Prelude> compare 1 2
LT
9
2022-06-07 15:08:25
Source

The stated remedies are great for really straightforward estimations, yet really mistake - vulnerable. Instances:

# without spaces expr 20+5 produces literally 20+5
expr 20+5
→ 20+5

# bc's result doesn't give the fractional part by default
bc <<< 9.0/2.0
→ 4

# expr does only integer
expr 9 / 2
→ 4

# same for POSIX arithmetic expansion
echo $((9/2))
→ 4

# bash arithmetic expansion chokes on floats
echo $((9.0/2.0))
→ bash: 9/2.0: syntax error: invalid arithmetic operator (error token is ".0")

# Most `expr` implementations also have problems with floats
expr 9.0 / 2.0
→ expr: non-integer argument

A syntax mistake like the last ones is conveniently seen, yet integer feedbacks with a thrown out float component can conveniently go undetected and also bring about incorrect outcomes.

That is why I constantly make use of a scripting language like Lua for that. Yet you can pick any kind of scripting language that you know with. I simply make use of Lua as an instance. The benefits are

  • an acquainted syntax
  • acquainted features
  • acquainted cautions
  • adaptable input
  • rooms generally do not matter
  • floating point result

Examples:

lua -e "print(9/2)"
→ 4.5

lua -e "print(9 / 2)"
→ 4.5

lua -e "print(9.0/2)"
→ 4.5

lua -e "print (9 /2.)"
→ 4.5

lua -e "print(math.sqrt(9))"
→ 3
30
2022-06-07 15:07:41
Source

You can make use of bc, Eg.,

$ echo "25 + 5" | bc
30

Alternatively bc <<< 25+5 will certainly additionally function.

Or interactively, if you intend to do greater than simply a solitary straightforward estimation:

$ 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'. 
25 + 5
30

The GNU execution of bc prints that header/copyright details on start - up when both its stdin and also stdout most likely to an incurable. You can subdue it with the (GNU - details) -q alternative. For additional information see the bc man page

20
2022-06-07 15:03:11
Source

There are great deals of alternatives!!!

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 make use of POSIX arithmetic development for integer arithmetic echo "$((...))" :

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

Quite portable ( ash dash yash bash ksh93 lksh zsh ): ¢ Using printf capacity to publish drifts we can expand most coverings to do floating point mathematics albeit with a minimal array (no greater than 10 figures):

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

ksh93 , yash and also zsh do sustain drifts below:

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

just ksh93 (straight) and also zsh loading collection mathfunc below:

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

(zsh demand to load zmodload zsh/mathfunc to get features 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 just):

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

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

; echo $:25/3
8

POSIX toolchest

bc (see listed below for interactive setting), manual here

Mnemonic: best calculator (though the b remains in reality for standard ).

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

(sustains approximate accuracy numbers)


bc interactive setting:

$ 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 is remedy, expr (no interactive setting):

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

Joshua's solution: awk (no interactive setting):

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

Other essentially mobile devices

Arcege is remedy, dc (interactive setting: dc):

Which is a lot more enjoyable given that it functions by reverse gloss symbols.

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

But not as sensible unless you collaborate with reverse gloss symbols a whole lot.

Keep in mind that dc precedes bc and also bc has actually been traditionally applied as a wrapper around dc yet dc was not standardised by POSIX


DQdims is calc (called for sudo apt-get install apcalc):

$ calc 2 + 4
6

General objective language interpreters:

manatwork is remedy, node (interactive setting: node ; result function not required):

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

Perl (interactive setting: perl -de 1):

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

Python (interactive setting: python ; result function not required):

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

Also sustains approximate accuracy numbers:

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

If you have clisp mounted, you can additionally make use of gloss symbols:

$ clisp -x "(+ 2 2)"

Marco is remedy, lua (interactive setting: lua):

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

PHP (interactive setting: php -a):

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

Ruby (interactive setting: irb ; result function not required):

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

Guile (interactive setting: guile):

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

S - Lang (interactive setting: slsh ; result function not required, simply a ; terminator):

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

Tcl (interactive setting: tclsh ; result function not required, yet expr is):

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

Javascript coverings:

$ 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 setting: 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 alternatives on mysql and also postgres stop the 'ascii art' photo!

Specialized mathematics - oriented languages:

R in simple setting - allows create 1000 Normal arbitrary numbers and also get the typical inconsistency and also print it

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

R making use of the littler manuscript - allows print pi made even

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

PARI/GP , a considerable computer system algebra system for number concept, straight algebra, and also several various other points

$ 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 - degree analyzed language, largely planned for mathematical calculations)

Also sustains intricate numbers:

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

Julia , high - efficiency language and also interpreter for clinical and also mathematical computer.

Non - interactive alternative:

$ julia -E '2.5+3.7'
6.2

GhostScript GhostScript is a PostScript interpreter, really generally mounted also in older distributions.¢ See PostScript docs for a checklist of sustained mathematics commands.

Interactive instance:

$ 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>
547
2022-06-07 14:59:41
Source

Since no - one else has actually stated it, and also though it is not purely a calculator (yet neither are all these basic - objective scripting languages), I would certainly such as to state units:

$ units "1 + 1"
        Definition: 2
$ units "1 lb" "kg"
        * 0.45359237
         / 2.2046226

Or, for much less result so you can get simply the number to make use of in $() to assign to something:

$ units -t "1 + 1"
2
$ units -t "1 lb" "kg"
0.4539237

And it also does temperature level conversions

$ units -t "tempC(20)" "tempF"
68

To get the temperature level conversion in an expression for more estimation, do this:

$ units -t "~tempF(tempC(20))+1"
68.1
12
2022-06-07 14:53:07
Source

SQLite :

echo 'select 1 + 1;' | sqlite3 

MySQL :

mysql -e 'select 1 + 1 from dual;'

PostgreSQL :

psql -c 'select 1 + 1 as sum;'
3
2022-06-07 14:50:14
Source

Nobody has stated awk yet?

Making use of POSIX shell features, and also awk mathematics power, simply specify this (one line) function:

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

Then simply execute points like calc 1+1 or calc 5/2

Note: To make the function constantly readily available, add it to ~/. bashrc (or your equivalent shell is start-up documents)

Of training course, a little manuscript called "calc" with the adhering to materials:

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

can additionally function.

31
2022-06-07 14:44:07
Source