I stumbled on geometric mean while on YouTube and decided to try my hand at designing an algorithm.
It seemed a bit lazy to just use arrays, so I went with a linked list. Unfortunately, I'm a bit out of practice with pointers. It's a bit sloppy, but it gets the job done.
Mean-stack was my first attempt. Using a stack was clearly the most straight-forward way to hold the numbers.
Mean was further refined to build a proper queue.
I expanded it for some simple statistical analysis and added some more switches.
The geometric mean uses two different algoritms.
The first uses pow() to compute the nth root of the product of n items. The product can get large quite quickly and we could end up with an overflow.
The second takes the anti-log of the sum of logs of the items divided by n. By using the log of each item we may sacrifice some precision here but will hopefully avoid any overflow situations.
mean - simple statistical analysis tool.
mean [-d] [-g] [-G] [-h] [-m] [-p] [-q] [-s] [-s] [-v]
Displays multiple statistics on a set of data taken from stdin.
Statistics currently include the count, range, sum, product, arithmetic and geometric means and the standard deviation on a report view, and most can be selected individually.
The program uses double for precision.
The geometric mean with logarithms should work for larger data sets; however, it takes the log of each number for the computation and precision may be sacrificed. If the product overflows, the other algorithm may not provide valid results.
|
-d |
Prints the standard deviation. |
|||
|
-g |
Prints the geometric mean. |
|||
|
-G |
Prints the geometric mean using logarithms. |
|||
|
-h |
Prints help message. |
|||
|
-m |
Prints the arithmetic mean (average). |
|||
|
-p |
Prints the product. |
|||
|
-q |
Surpresses the prompt. |
|||
|
-s |
Prints the sum. |
|||
|
-v |
Prints the version. |
Any options chosen will surpress the prompt.
Input is taken from stdin. Numbers should be on separate lines. The list can be terminated with Ctrl-d on a new line when input from the console.
Returns 0 on success, 1 on bad option, 2 on other errors.
Values are not checked for validity. A non-numeric value will be interpreted as zero.
The geometric mean is undefined if the data set includes negative numbers or zero.
The geometric mean is undefined if there are less than two values in the data set.
The product can become out of range on larger data sets. No check is done to see if values have gone out of range.
Michael J. Chappell
Version 0.2 updated 31 October 2025