Quick-n-Dirty Math from the Shell

Saturday, January 23rd, 2010 at 10:46 pm | 7,413 views | trackback url

Casio fx-115ES CalculatorI find myself needing to whip out a calculator a dozen times a day, but my calculator is never at my fingertips when I need it and the “Calc” application on my BlackBerry is too clunky to use with the trackball. I needed a faster way to do some quick math when I’m around the laptops I use every day.

Did I mention I’m horrible at math? Yes, it’s true. I’ve been working with computers for the last 2 decades, and I still struggle with some intermediate and complex math concepts. But that’s why we have computers and calculators, right?

I’m used to using bc(1) for all of those quick and dirty needs, but it requires that I load it up in an interactive fashion. It looks like this:

bc in Interactive Mode

$ bc
bc 1.06.94
Copyright 1991-1994, 1997, 1998, 2000, 2004, 2006 Free Software Foundation, Inc.
This is free software with ABSOLUTELY NO WARRANTY.
For details type `warranty'. 
19931424 / 1024

I have to type each line one at a time. It’s effective, but clunky because it is manual and interactive. So I started looking around for other ways to do this, that weren’t so complex and could be done non-interactively.

bc in non-interactive mode

bc(1) doesn’t have a non-interactive mode as an option, but you can pipe things into it:

Simple math using pipes:

$ echo '(2+2)' | bc
$ echo '7+(6*5)' | bc

Square root:

$ echo 'scale=30;sqrt(2)' | bc

Convert from hexidecimal to decimal:

$ echo 'ibase=16;obase=A;FE' | bc

Binary to decimal:

echo 'ibase=2;obase=A;10' | bc

Using a redirect syntax:

$ bc -l <<< '10.5 + 1.5'

You get the idea. But as I started tinkering more with the shell, I discovered a few other ways to do simple math without using bc. If you’re using Bash as your shell, you can do math directly in the shell there as well:

Using expr(1) from Bash

$ expr 19931424 / 1024
expr 2 + 2

Using bash itself

$ echo $[2 + 2]
echo $((2 + 2))

Math with Perl one-liners

Simple addition:

$ perl -le 'print '2+2''

Complex addition:

$ perl -le 'print 2+2+(5+100)'

Square root:

$ perl -le 'print sqrt(64);'

Pretty simple and effective, and does not require you to interact with it directly.

Last Modified: Sunday, March 6th, 2016 @ 02:35

Leave a Reply

You must be logged in to post a comment.

Bad Behavior has blocked 1352 access attempts in the last 7 days.