A desk calculator with formula definition

Lew Mammel, Jr. lew at ihuxr.UUCP
Sat Dec 8 05:49:33 AEST 1984


Some time ago I wrote a simple desk calculator for myself using Yacc and
Lex, as suggested by the example in the Yacc document. My excuse was that
I wanted a simple floating point capability, with trig and fractional
powers, which dc and bc don't provide.  I also provided for arbitrary length
variable names; a huge improvement over bc in my opinion.

Some time later, I enhanced it with a formula definition capability.
I can type a line like:

#define alpha "(1 - beta^2)^.5)"

Then, whenever I type "alpha" (not including quotes of course) it is expanded
into the formula. It works by saving the string and then "unputting" it
into the input stream when the defined token is read. It took me a while
to get this scheme straight in my own mind, but when I finally did I found
that Lex was ready and waiting for me with just the right function. It
was quite simple to implement.

Since it unputs the defined strings into the actual input stream, nested
substitution works with no sweat.  There is no guard against self-definition,
however, which causes "yacc stack overflow".

I can put a bunch of these definitions in a file and use them in an
interactive session with the command line:

cat file.defs - | calc

I used a file like this when I did some calculations on the brightness
of venus:

#define PI "3.1415926535"
#define theta "t*PI/180"
#define x "((1+A^2-2*A*cos(theta))^.5)"
#define b "((A+x)^2-1)/2/A/x^3"
A=.723

With these initializations I can type say, "t=45" then type "b", and the
defined value of "b" will be displayed. I can then alter "A" by typing
say, "A=.5" and then see the new value of "b" by typing "b" again. I should
mention that the results I posted to net.astro were from a C program, but
I used my calculator for "messing around" with the formula.

I have found this convenient to use, and as I said, it was very easy
to implement. Since it's written in Yacc and Lex, alterations and enhancements
can be made easily, as well.

	Lew Mammel, Jr. ihnp4!ihuxr!lew

P.S.  This is my last day on ihuxr. I'll be at ihnp4!ihlpa soon, but net
	and mail availability may be shaky for a while.



More information about the Comp.unix mailing list