Bash Math: Difference between revisions
From charlesreid1
No edit summary |
|||
| Line 121: | Line 121: | ||
{{Programs}} | |||
{{Unix Programs}} | |||
{{Math Programs}} | |||
Revision as of 15:34, 28 May 2011
Basic Math
Bash has some built-in functionality for really basic integer math, like addition, subtraction, multiplication, and division.
Addition
$ sum=$((2+2)) && echo $sum
4
$ sum=$((sum+10)) && echo $sum
14
Subtraction
$ diff=$((100-50)) && echo $diff
50
$ diff=$((diff-25)) && echo $diff
25
Multiplication
$ prod=$((2*8)) && echo $prod
16
$ a=9; b=3; prod=$((a*b)) && echo $prod
27
Division
$ a=14; b=2; div=$((a/b)) && echo $div
7
Remainder
$ a=10; b=4; z=$((a%b)) && echo $z
2
Exponentiation
$ z=5 && echo $z
5
$ zz=$((z**2)) && echo $zz
25
Complex Math
To do anything more complex than basic integer math, you have to use the program bc (bash calculator).
Operators
You can use the increment and decrement operators ++ and -- as follow:
Increment++
The increment operator can be used as either a prefix or postfix operator, i.e. as ++i or i++. Example:
$ z=1 && echo $z
1
$ ((++z)) && echo $z
2
$ ((++z)) && echo $z
3
$ ((++z)) && echo $z
4
This can be used in bash for loops as follows:
for ((i=1; i <=$NUM ; i++)); do
echo $i
done
Decrement--
Like the increment operator, this can be a prefix or postfix operator, i.e. --i or i--:
$ z=1 && echo $z
1
$ ((--z)) && echo $z
$ ((--z)) && echo $z
-1
$ ((--z)) && echo $z
-2
$ ((--z)) && echo $z
-3
Notice that echo $z doesn't print anything if z=0.
| GNU/Linux/Unix the concrete that makes the foundations of the internet.
Compiling Software · Upgrading Software Category:Build Tools · Make · Cmake · Gdb Bash Bash · Bash/Quick (Quick Reference) · Bash Math Text Editors Text Manipulation Command Line Utilities Aptitude · Diff · Make · Patch · Subversion · Xargs Security SSH (Secure Shell) · Gpg (Gnu Privacy Guard) · Category:Security Networking Linux/SSH · Linux/Networking · Linux/File Server Web Servers
|
| Scientific Computing Topics in scientific computing.
Numerical Software: Lapack · Sundials · Matlab · Octave · FFTW Petsc · Example Petsc Makefile · Trilinos · Hypre · Ginac · Gnuplot
Python: Numpy · Scipy · Pandas · Matplotlib · Python Sundials · Py4Sci Scikit-learn: Sklearn · Skimage
|