[zsh] Command line math functions
$ zmodload zsh/mathfunc $ echo $(( sin(1/4.0)**2 + cos(1/4.0)**2 - 1 )) -1.1102230246251565e-16 $ echo $(( pi = 4.0 * atan(1.0) )) 3.1415926535897931 $ echo $(( f = sin(0.3) )) 0.29552020666133955 $ print $((1e12 * rand48())) 847909677310.23413 $ print $(( rand48(seed) )) 0.0104348833470027
Notice that zsh/mathfunc must be loaded first!
Credit: copied from zsh-lovers.
[awk] Command line calculator using awk
This is an update on our bash command line calculator posted a few days ago — except for the fact that this time we’ll use awk to do the calculation instead of bc. As I mentioned in that post, you may use python or ruby (irb) to do the same thing, but these tricks may be useful if you don’t have ruby or python installed (bc and awk, in general, come by default in any Unix or GNU/Linux distro).
First, create (or rewrite if you used our last trick) function “?” as follows and put it in your ~/.bashrc file:
? () { awk "BEGIN{ print $* }" ;}and make sure to reload your ~/.bashrc file (do the similar thing if you're using any other shell). [NOTE: ZSH does not like ``?'' as a function, so you might consider replacing it with something reasonable, e.g., ``compute'']
Now, if you want to calculate an expression, do it, for example, as
$ ? "2*3+4.0*(9.9+8.1)"and don’t forget the quotes.
.
The advantage of this over bc is that you can use more arithmetic and trigonometric functions (link):
atan2(y,x) Arctan of y/x between -pi and pi. cos(x) Cosine function, x in radians. exp(x) Exponential function. int(x) Returns x truncated towards zero. log(x) Natural logarithm. rand() Returns a random number between zero and one. sin(x) Sine function, x in radians. sqrt(x) Returns square root of x.
.
You may include variables as well in the function definition itself:
? () { awk "BEGIN{ pi = 4.0*atan2(1.0,1.0); degree = pi/180.0; print $* }" ;}where we have defined the variable pi and degree (such that tan(pi/4.0) = 1.0 and pi radians is equivalent to 180 degrees) to be used later, e.g.
$ ? "cos(pi)"
$ ? "cos(90*degree)"and I’m sure that you’ll get -1 and 0 (within the machine precision), respectively, as the answer!
(You may find some more interesting calculator related tricks posted in this blog scattered in different pages)
Credit: here and here (via LifeHacker).
UPDATE: I just realized that I can use the calc package (besides bc, awk, python and irb) to do the command line math wizardry more efficiently (and let’s take that as the end to this command line calculator series!). It has a larger set of built-in functions. You may grab the source code from the maintainer’s website and follow my instructions to install it on your system [although binaries are also readily available, e.g. apcalc package for Ubuntu 9.10 (Karmic Koala)].
[vim] Simple calculator in vim
Need a simple calculator during editing a file using vim and don’t want to click away from it? Then first add the following to your ~/.vimrc:
imap <silent> <C-C> <C-R>=string(eval(input("Calculate: ")))<CR>In order to use the calculator while you are editing some file using vim, hit CTRL-C in the insert mode and then enter what you want to calculate (e.g., 2+3 or 4.5*7.9).
(It) first calls the built-in
input()function to request the user to type in their calculation, whichinput()then returns as a string. That input string is then passed to the built-ineval(), which evaluates it as a Vimscript expression and returns the result. Next, the built-instring()function converts the numeric result back to a string, which the key-mapping’s<C-R>=sequence is then able to insert.
Reference: here.
[bash] Command line calculator
Add the following function to the ~/.bashrc or ~/.bash_aliases, source the former and you’ll get a better command line calculator:
? () { echo "$*" | bc -l; }
You can use it the following way:
$ ? 7*3-5.5
and, no doubt that you’ll get 15.5 as the answer.
N.B. If you use parentheses, you must enclose the whole expression by double quotes.
UPDATE: An alternative way of using bc
$ bc -l <<< "7*3 - 5.5"
[bash] Introductory BASH scripting for scientists
These are based on the type of work I am interested in, i.e. scientific programming: you won’t see much about character strings in this post since we are mostly interested in numbers!
These can all be directly typed in the BASH prompt. Semicolons basically indicate the start of a new statement: you may put them in separate lines; and in that case, do not put the semicolon between the statements typed in different lines. The dollar sign ($) at the beginning of the command line indicates the command prompt and it is not a part of the command!
1. The basic
Print the sum of two integers:
$ echo $((2+3))
The two pairs of parentheses interpret them as numbers. You can also use square brackets (just a single pair):
$ echo $[2+3].
For floating point numbers use bc.
Variable substitutions may be done as
$ num1=10; num2=20; echo $(($num1+$num2))
(no space between the equality sign and the variable/number)
2. Conditional block: arithmetic conditional operators are eq, lt, le, gt and ge:
$ i=10; j=20; if [ $i -lt $j ]; then echo "$i<$j? True"; fi
$ i=$RANDOM;j=$RANDOM; if [ $i -lt $j ]; then echo "i=$i is less than j=$j"; else echo "i=$i is NOT less than j=$j";fi
($RANDOM equals a random number at each invocation)
Notice the spaces between the square brackets and the expression within it.
3. Array:
Assignment:
$ arr=(10 11 12)
which is the same as
$ arr[0]=10; arr[1]=11; arr[2]=12
Following constructs show how you can actually access the array (link)
$ echo ${arr[2]} # The 3rd element of the array
$ echo ${arr[*]} # All of the items in the array
$ echo ${!arr[*]} # All of the indexes in the array
$ echo ${#arr[*]} # Number of items in the array
$ echo ${#arr[0]} # Length of item zero
4. For loop
$ for (( c=1; c<=5; c++ )); do echo "c = $c"; done # C-style
$ for c in 1 2 3 4 5; do echo "c = $c"; done # List
$ arr=(1 2 3 4 5); for c in ${arr[*]}; do echo "c = $c"; done # Explicit array
$ for c in {1..5}; do echo "c = $c"; done # 1 thru' 5 with unit intervals
$ for c in {0..10..2}; do echo "c = $c"; done # 0 thru' 10 with interval=2
5. While and until loops
$ c=0; while [ $c -lt 10 ]; do echo "c = $c"; let c++; done
You may replace “let c++” by “((c++))”.
$ c=20; until [ $c -lt 10 ]; do echo "c = $c"; let c--; done
6. User input
Use read command to read in user input, e.g.
$ echo "Enter two integers"; read num1 num2; echo "$num1+$num2=$((num1+num2))"
In the second echo statement, when num1 and num2 are not enclosed within two pairs of parentheses they are treated as character strings, whereas in the last part the double parentheses cause them to be treated as numbers.
N.B. For the above loops and blocks, a line break between do or then and the statement that immediately follows it is allowed.
Reference: link.

leave a comment