Quick tip: The handy command line calculator
[WSL]: Windows Subsystem for Linux — Who needs a GUI to do math when we have options for Unix-like (MacOS, Linux, etc.), Command Prompt, and PowerShell? #Unix-like OSs
Unix-like OSs, including macOS, WSL, and Linux, include an awesome calculator called bc. From the man page:
bcis a language that supports arbitrary-precision numbers with interactive execution of statements. There are some similarities in its syntax to the C programming language. A standard math library is available via a command-line option. If requested, the math library is defined before processing any files.
bcstarts by processing code from all the files listed on the command line in the order listed. After all the files have been processed,bcreads from standard input. All code is executed as it is read. The only caveat is the file input: you can't just pass in parameters… but you can useechoto pass in the equation. For example:echo '1 + 2 + 3 + 4' | bc
10
bccan also work with different number bases, for example:echo "obase=2; ibase=10; 42" | bc
101010
obasestands for output base, andibasestands for input base. So in the example, we’re converting 42 (base 10) to binary.Floating-point division is a weirdness with
bc. For example, you would expect the answer to be 0.4 below, but it is 0:echo "2/5" | bc
0The solution is to use the math library switch
-l:echo "2/5" | bc -l
.40000000000000000000And if you want 20 decimal places, you can use
scaleto control it:echo "scale=3; 2/5" | bc -l
.400
Windows Command Prompt
Command Prompt has a similar tool using the set /a command:
set /a 3+3
6
set /a (3+3)*3
18
set /a "203>>3"
25
PowerShell
PowerShell natively supports some basic functionality, but if you want to use more advanced functionality, you can use the entire System.Math class for a wide range of operations:
4 + 5
9
6 * 7
42
[Math]::Sin(50)
-0.262374853703929
[Math]::Max([Math]::Tan(40), [Math]::Cos(40))
-0.666938061652262