Submit Hint Search The Forums LinksStatsPollsHeadlinesRSS
14,000 hints and counting!

Yet another command line calculator UNIX
Python is included in OS X. It has an interactive mode that works very well as a calculator, as seen here. In the Terminal, launch Python as shown, and then type in the commands next to the >>> and ... prompts.
$ python
Python 2.3 (#1, Sep 13 2003, 00:49:11) 
[GCC 3.3 20030304 (Apple Computer, Inc. build 1495)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> 45*3
135
>>> quit
'Use Ctrl-D (i.e. EOF) to exit.'
$
Since it is a complete programming language, you can write functions to calculate virtually anything. The following example is from the More Flow Control Tools section of the Python manual:
>>> def fib(n):    # write Fibonacci series up to n
...     """Print a Fibonacci series up to n."""
...     a, b = 0, 1
...     while b < n:
...         print b,
...         a, b = b, a+b
... 
>>> # Now call the function we just defined:
... fib(2000)
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597
[robg adds: Note that in the example above, those are tabs inserted after the ..., and they're very important. Without them, you'll get an error (can you tell I haven't used Python much??)]
    •    
  • Currently 1.33 / 5
  • 1
  • 2
  • 3
  • 4
  • 5
  (3 votes cast)
 
[12,423 views]  

Yet another command line calculator | 20 comments | Create New Account
Click here to return to the 'Yet another command line calculator' hint
The following comments are owned by whoever posted them. This site is not responsible for what they say.
Another way with bash
Authored by: tflight on Feb 02, '05 10:05:34AM
I added the following to my .bash_profile file to accomplish something similar:
function calc () {
        awk "BEGIN { print $* ; }"
}
Then you can bring up the terminal and type things like "calc 9*9" or "calc 3^3" which will return 81 and 27, respectively.

Your .bash_profile file is located in your home directory. In the terminal you can type "cd ~" to make sure you are in your home directory then use a text editor like pico "pico .bash_profile" to edit the file. After saving the file (control-x) you will need to log out and back in for the changes to take effect.

[ Reply to This | # ]

Another way with zsh
Authored by: adrianm on Feb 02, '05 01:43:26PM
if using zsh, try having a function like this

function calc {
  print $(($*))
}
and then you can type, eg calc 9+3

Of course you could also just type print $((9+3)) but that would just spoil the fun.

[ Reply to This | # ]

Another way with csh/tcsh
Authored by: winswitcher429 on Feb 02, '05 03:55:54PM

I have an alias setup in my .cshrc file that looks like this

alias calc 'echo " scale=4;\!*" | bc'

You can then from the command line type in

%calc 5 * 45 + ( 324 - 17 ) / 15
245.4666
%

What's really cool about almost ALL of these hints is that they work on almost ALL Unix versions. I also have this setup on my OpenStep, Solaris and Linux machines and this works that same on all of them



[ Reply to This | # ]
Yet another command line calculator
Authored by: mkhaw on Feb 02, '05 11:01:10AM

One could also use the Unix 'bc' calculator program, which supports C-like expressions including control flow and function definitions. Try 'man bc' for details.

From a shell prompt you can say things like:

csh% echo '3*4' | bc
12
csh%



[ Reply to This | # ]
Yet another command line calculator
Authored by: ericasadun on Feb 02, '05 12:37:22PM

You can use bc interactively, line-by-line.

There's also "dc" which is reverse polish.



[ Reply to This | # ]
Yet another command line calculator
Authored by: zojas on Feb 02, '05 01:37:49PM

the cool thing is that bc is 'infinite' precision. try this:

bc -l
2^100
1267650600228229401496703205376

yup, that's 2 raised to the 100th power!

the -l flag turns on floating point stuff, to 20 decimal place precision.



[ Reply to This | # ]
Yet another command line calculator
Authored by: nicholst on Apr 09, '06 10:54:44AM
Why bother with echo? With this alias

alias calc bc -lq

I always have a calculator handy.

The -l option is important, otherwise you only get integer arithmatic. (-q just silences the FSF warning).

-T

[ Reply to This | # ]

Yet another command line calculator
Authored by: aaronrp on Feb 02, '05 11:41:35AM
Did we talk about Perl yet? Some tcsh aliases:

alias ? "perl -e 'print \!* , qq/\n/'"
alias ?? "perl -e 'print join ( qq/\n/, \!* ) , qq/\n/;'"
The second one allows you to print arrays -- useful for Perl's built-in arrays, like @INC (which contains the locations where Perl will look for modules). I used ? since it hearkens back to old BASIC days...

[ Reply to This | # ]
Yet another command line calculator
Authored by: kenahoo on Feb 02, '05 12:48:11PM

For that second one, you might be happier with:

alias ?? "perl -le 'print shift().q{,} while @ARGV>1; print for @ARGV"

because it won't get messed up by funny characters (quotes, perl operators, etc.) in the strings you're passing to it.

I did a few strange things there to avoid having to use more quotes and figure out how to escape them - the equivalent one-liner could be shortened to:

perl -le 'print map "$_,\n", @ARGV'

-Ken



[ Reply to This | # ]
Yet another command line calculator
Authored by: boredzo on Feb 02, '05 11:45:52AM

a better way to do that fib function in version 2.3 or later of Python, instead of print, is the yield statement

yield b

(note that there is no comma at the end like there is at the end of the print statement in the print version.)

for my calculations, though, I use calc, by Landon Curt Noll. its syntax resembles C in many ways (the only major difference being the use of an xor() function instead of the ^ operator, which is reverted to exponentiation). its big advantage is that it is arbitrary precision, so it is always accurate - no roundoff error, and every number is supported. try 2 to the power of 128 in some other calculator sometime. ☺



[ Reply to This | # ]
Yet another command line calculator
Authored by: delza on Feb 02, '05 12:50:28PM

There's a very interresting language called Frink which specializes in calculations while retaining (and converting) the units you are calculating in.

http://futureboy.homeip.net/frinkdocs/

It doesn't come pre-installed on OS X, but it installs easily and is handy for conversion-related calculations without going to the trouble to look up the conversion ratios themselves.



[ Reply to This | # ]
Yet another command line calculator
Authored by: jaysoffian on Feb 02, '05 07:29:10PM
You can also use "units" which comes with OS X:
callisto-soffian-org:~% units
500 units, 54 prefixes
You have: 10 kilometers
You want: miles
        * 6.2137119
        / 0.1609344
You have: ^D
callisto-soffian-org:~% 


[ Reply to This | # ]
Yet another command line calculator
Authored by: delza on Feb 02, '05 01:27:30PM

Another tip for using Python from the command-line: for short scripts you don't need to start the interactive editor, you can just pass the script to the interpreter with -C, but you will have to print the results explicitly.

For example:

# 2 to the power of 16
python -c "print 2 ** 10"

# hex representation of 1024
python -c "print hex(1024)"

# base-10 representation of 0x400
python -c "print int('0x400', 16)"

# cosine of pi/4
python -c "import math; print math.cos(math.pi * 0.25)"

etc...



[ Reply to This | # ]
Yet another command line calculator
Authored by: adrianm on Feb 02, '05 01:50:10PM
I presume we've already covered applescript?

osascript -e '3+4/8'
And you can use the Services menu when in most text boxes (incl. TextEdit, Pages, etc) to evaluate any applescript expression.

[ Reply to This | # ]
Yet another command line calculator
Authored by: KingDoom on Feb 02, '05 02:05:38PM

These are fantastic hints!

I hate using the Calculator app that comes bundled with OS X, using the terminal feels so much more natural.



[ Reply to This | # ]
Yet another command line calculator
Authored by: bimtob on Feb 02, '05 07:04:43PM
Sarcasm?
Anyway, another way...you can do this in Bash:

[~]$ echo $((expression))

so...
[~]$ echo $((5*8))
40



[ Reply to This | # ]
Python = teh yuck
Authored by: Lectrick on Feb 03, '05 09:08:28AM

Ah, Python, with its retarded "significant whitespace." Try Ruby instead ;) /flame-on

---
In /dev/null, no one can hear you scream



[ Reply to This | # ]
Python = teh yuck
Authored by: pete23 on Feb 03, '05 12:48:59PM

yeah, beat me to the punch. irb-tastic...



[ Reply to This | # ]
Python = teh roxx0rz
Authored by: jimhill on Feb 05, '05 01:22:08PM

I used to complain about Python's indentation scoping requirement, then I realized that every programmer worth his salt already uses whitespace for scoping. The real benefit comes when you're working on multi-programmer projects...I've never been able to read someone else's code as quickly and comprehensibly as when it's in Python.

This is by no means a shot at Ruby (which is a wonderful language in its own right), just a comment that the most typical "negative" I see levied toward Python is actually a tremendous positive.

Oh, and Rob: You really owe it to yourself to learn Python. How's that for a hint?


---
Mac OS X: Because making UNIX simple is easier than debugging Windows.



[ Reply to This | # ]
Beware of divisions!
Authored by: fabrizio on Feb 03, '05 02:22:08PM

Python as a default gives you the integer part of a division, i.e. if you type 5/2, it gives 2 as result. You could type 5.0/2 and it would give the floating point result, but it's quite annoying. You could resolve defining a shell alias so that python is launched with the -Qnew switch. In tcsh you would add this alias to your "~/.tcshrc" file:

alias python 'python -Qnew'



[ Reply to This | # ]