Skip to content
Snippets Groups Projects
README 1.36 KiB
Sum NumberRs "Ganska Lagom"
===========================

This program is an attempt to sum numbers in a more accurate way than
this naive awk script:

    awk '{s+=$1} END {print s}'

The problem is that if you add a lot of small numbers, sooner or later
the sum will be so large that rounding errors will cause an error in
the sum.  (We are talking floating point numbers here, not integers).

This program reads all numbers, sorts them, and than adds the two
smallest numbers.  The result is inserted in the proper place among
the remaining numbers, and the two smallest numbers are added once
again.  The process repeats until only one number remains: the sum.

As long as you only have positive numbers, this algorithm should work
fairly well.  If you have negative numbers, it will work just as well,
since the program sorts the numbers based on the absolute value of the
numbers.  If, however, you have both positive and negative numbers,
the algorithm may not give you the best possible accuracy.

There are probably faster ways to obtain equally good results.

"Lagom" is Swedish for "just right".  "Ganska lagom" means "not
exactly right, but close enough", and in this case it refers to the
accuracy when both positive and negative numbers are used.  It also
refers to the algorithmic speed.

Warning: If you plan to use this for serious work, you should extend
the test suite.