WAM macro for dc

Home
WAM is a macro for dc (Unix's classic programmable RPN calculator) that lets you find out the weighted arithmetic mean of an arbitrarily long sequence of numbers.

Here it is, in its most compact (and least human-readable) form:

[0Sw0Sp[d0=qdSw*Lp+SpLwLw+Swlax]Sa[LpLw/+q]SqlaxLaX+LqX+]Sw

Read the extensively commented source code if you are interested in its inner workings.

The compact form can be conveniently pasted into a running instance of dc, or - better yet - into an initialization file, if your installed version allows such a mechanism. For example, GNU dc allows a script file to be read before accepting input from STDIN. Like this:

$ dc -f ~/etc/my_macros.dc -

How to use WAM

After loading the macro into dc, the general usage pattern is:
0 datum1 weight1 datum2 weight2 ... ... datumn weightn lwx p
The initial 0 is a sequence terminator (first in, last out!). When encountered while consuming the stack, it marks the end of datum/weight pairs: this allows for an arbitrary number of pairs. The lwx means: load macro w (WAM itself) and execute it. The final p prints the result.

Compatibility

According to documentation I've read, WAM should be compatible with all dc versions since Unix V7 (included). It's been tested on GNU dc and OpenBSD's dc.

dc
“WAM macro for dc” is Copyright © Dario Niedermann
released with NO WARRANTY under the terms of the GPLv3 license.

HomeValid HTML 4.01 Strict Valid CSS!