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 the dc version you use 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 the macro is consuming the stack, it marks the end of datum/weight pairs: this allows for an arbitrary number of pairs. Note that the 0 takes the place of a weight: having a datum/weight pair with a null weight would be pointless, therefore we can use 0 as the terminator. 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.

Requires: dc
“WAM macro for dc” is Copyright © Dario Niedermann
released with no warranty under the terms of the GPLv3 license.
Home Valid HTML 4.01 Strict  Valid CSS!