Hi Tim,

> Thank you Ralph for mentioning dc at the pub meet last night - really
> useful little application.

Don't let Nathan hear you.  He thinks I turn every problem into one that
needs dc(1) in its solution as it is.  One little use for it is
~/bin/sum to tot-up numbers.

    $ cat ~/bin/sum
    #! /bin/sh

    (
        echo 0
        sed 's/$/+/' "$@"
        echo p
    ) |
    dc |
    tr -d '\\\n'
    echo
    $ 

(dc splits long numbers over multiple lines, e.g. `dc
<<<'9d*d*d*d*d*d*d*d*p'' so the tr(1) splices them together again.)

Given something that gives us some random numbers,

    $ gen()
    > {
    >     tr -dc '[:digit:].\n' </dev/urandom |
    >     tr -s '.\n' |
    >     egrep -v '(^\.*$)|\..*\.'
    > }
    $ gen | sed 3q
    8707145.3
    7787948
    1
    $

dc gives perfect results compared with the staple `awk '{s += $0} END
{print s}'' I used to use.

    $ gen | sed 10000q | sum
    
673447484222598337164521904782497110322692898946797077.47176958323007182340078619980536635679245283890

awk's use of floating-point has repeatedly caught me out over the years.

> There's also rpncalc in the Debian repos (HP28 emulator) which has the
> trig functions missing in dc and handles hex a bit more elegantly.

Thanks, I'll take a look.

Cheers,
Ralph.


--
Next meeting: Bournemouth, Wednesday 2010-08-04 20:00
http://dorset.lug.org.uk/     http://www.linkedin.com/groups?gid=2645413
   Chat: http://www.mibbit.com/?server=irc.blitzed.org&channel=%23dorset
           List info: https://mailman.lug.org.uk/mailman/listinfo/dorset

Reply via email to