A numeric array class specification with implementations

This was inspired by a suggestion by Rozita Sheibani.

The following is an exercise in software design intended for teaching purposes. We will consider a class representing a collection of real numbers, such as measurements obtained from a sensor. For example, a sensor may periodically record a temperature, pressure, voltage, or other physical quantity, and we may wish to analyze the measurements that have been collected.

In many such applications, new measurements are continually added to the collection, but there is no need to go back and modify previously recorded values. Once a measurement has been recorded, it remains unchanged. Instead, we are interested in extracting information from the data, such as its minimum and maximum values, mean, standard deviation, and median.

This restriction is important. By allowing elements to be added but not subsequently modified or removed, we can consider alternative internal representations that maintain information about the data as new elements arrive. Such representations may make some operations more complicated, but allow other operations to be performed much more efficiently.

Although this is a relatively simple class, it provides an opportunity to explore an important principle of object-oriented programming: the distinction between what a class does and how it is implemented. In particular, we will see how two different internal representations of the same information can lead to substantially different implementations and run times, even though both satisfy exactly the same requirements.

This specification will allow users to store data in the order in which it is received, using the append(...) member function, or to insert new values as though the array were sorted, using the insert(...) member function. Some users may wish to maintain their data in sorted order, while others may have no need to do so. Appending new values is generally much faster than inserting them in sorted order, as insertion may require shifting many of the existing elements to make room for the new value. The specification will, however, require a member function to sort the given data if requested.

Specification

We begin with a requirements specification. This document describes the public interface and the expected behaviour of the class without specifying how the information must be stored internally. In other words, it describes what the class must do, not how it must do it:

Numeric array class specification

Designs

We will then examine two possible designs, both satisfying the same requirements.

Design 1: storing the array and calculating statistics when requested

The first design, Numeric_array_1, stores the elements of the array together with information about its size, capacity, and whether or not it is sorted. Adding a new element is relatively straightforward: we simply add the element to the array, increasing the capacity if necessary, and update the sorted status.

However, when we request the minimum, maximum, mean, or standard deviation, the class must generally examine the elements of the array to calculate the requested result. For example, calculating the mean requires adding all the elements and dividing by the number of elements. Calculating the standard deviation requires additional calculations involving the individual elements.

The minimum and maximum can be found immediately if the array is sorted, but otherwise they too require examining the elements of the array:

Design 1: calculating statistics when requested

Design 2: maintaining information as elements are added

The second design, Numeric_array_2, stores the same array and its associated information, but also maintains the sum of all elements, the sum of their squares, and the indices of the minimum and maximum elements.

This makes adding elements more complicated. Whenever a new element is added, we must update the sums and ensure that the indices of the minimum and maximum elements remain correct. In particular, inserting an element may shift existing elements to new positions, so the stored indices must be updated appropriately.

However, once this information is maintained, finding the minimum, maximum, mean, and standard deviation becomes straightforward. These operations no longer require loops that examine every element of the array. Instead, they can be calculated directly from the information already stored:

Design 2: maintaining statistics as elements are added

Implementations

You can examine the C++ implementations of both classes, together with programs demonstrating their use, in the source directory. Notice that the two classes provide the same public operations, even though their internal representations and implementations are different.

Both implementations allow values to be appended or inserted, but do not allow existing elements to be modified or removed. This restriction is what makes it practical for the second implementation to maintain summary information as elements are added.

Important

The most important takeaway from these implementations is that if either class were simply renamed Numeric_array, it would be very difficult for a user to determine which implementation was being used simply by examining the public interface. Both classes satisfy the same requirements, and a program using the class should obtain the same results regardless of which implementation is used.

However, the run times of the operations may be significantly different. The choice of internal representation affects not only how difficult the member functions are to implement, but also how efficiently those member functions execute.

Comparisons

Consider the advantages and disadvantages of the two designs:

  1. Calculating statistics when requested: The first design makes appending and inserting elements relatively straightforward. We simply store the new element and maintain the necessary information about the array.

    However, calculating the mean or standard deviation requires examining all the elements. Finding the minimum or maximum also requires examining all the elements if the array is not sorted. Thus, these operations have run times that grow proportionally with the number of elements in the array.

    If the array contains millions of measurements, and we repeatedly request the mean or standard deviation, we must repeatedly examine those millions of measurements, even if no new elements have been added.

  2. Maintaining statistics as elements are added: The second design requires more work whenever an element is appended or inserted. We must update the sum of the elements and the sum of their squares, and maintain the indices of the minimum and maximum elements. Inserting an element requires additional care because existing elements may be shifted to new positions.

    However, the minimum, maximum, mean, and standard deviation can now be determined without examining the entire array. Each of these operations requires only a fixed amount of work, regardless of how many elements have been stored.

    The additional bookkeeping does not change the asymptotic run time of appending an element when no reallocation is required, nor does it change the worst-case run time of inserting an element, which may already require shifting many elements.

    One disadvantage is that calculating the standard deviation from the sum and the sum of squares can be less numerically accurate for certain collections of floating-point values. Thus, improving the run time of an operation may introduce other considerations.

Neither design is inherently incorrect. Both satisfy the same requirements, but the choice of representation determines where the work is performed. The first design does less work when elements are added and more work when statistics are requested. The second design does more work when elements are added so that subsequent statistical queries require much less work.

This document compares these two designs, considering the complexity of adding elements, calculating statistics, maintaining additional information, and the resulting run times.

Other possible statistical operations

We have deliberately restricted this exercise to a small collection of statistical operations: finding the minimum and maximum, calculating the mean and standard deviation, and determining the median. These operations were selected because they illustrate different implementation approaches and run-time requirements. They are not intended to represent a comprehensive collection of statistical tools.

There are many other useful operations that could be implemented for a collection of real numbers. For example:

  1. Range: The difference between the maximum and minimum values. This provides a simple measure of the spread of the data.

  2. Variance: The average squared deviation from the mean. This is closely related to the standard deviation, which is the square root of the variance.

  3. Skewness: A measure of the asymmetry of the distribution of the data. A distribution may have a longer tail toward larger or smaller values.

  4. Kurtosis: A measure related to the weight of the tails of a distribution, often used to investigate the occurrence of extreme observations.

  5. Quantiles and percentiles: Values that divide the sorted data into specified proportions. The median is one example, dividing the data into two halves.

  6. Interquartile range: The difference between the third and first quartiles, providing a measure of the spread of the middle half of the observations.

  7. Mode: The value or values occurring most frequently in the collection. This is particularly useful when measurements take on repeated values.

  8. Counts and proportions: The number or proportion of measurements satisfying a particular condition, such as exceeding a threshold or falling within a specified interval.

  9. Root mean square: The square root of the mean of the squares of the elements. This is especially useful in applications involving electrical signals and other physical measurements.

Some of these operations could also benefit from maintaining additional information as elements are added. For example, the root mean square can be calculated directly if we already maintain the sum of squares. Other operations, such as determining arbitrary quantiles, may require access to the individual elements and additional processing.

We will not implement these additional operations here. The purpose of this exercise is to understand how the choice of an internal representation affects the design and efficiency of a class, not to develop a comprehensive statistical package.

Comments and disclaimer

The purpose of this exercise is not to develop a production-quality statistical library. Rather, it is to illustrate how the choice of an internal representation affects the complexity and run time of an implementation.

In particular, the decision to allow elements to be added, but not modified or removed, makes it possible to maintain additional statistical information incrementally. This is a useful design approach in applications where data are collected over time and subsequently analyzed.

By keeping the public interface independent of the internal representation, we can change the implementation without requiring changes to the programs that use the class. This separation between interface and implementation is one of the important benefits of object-oriented programming.

This exercise and its underlying ideas are those of Douglas Wilhelm Harder, expanding on a suggestion by Rozita Sheibani. The requirements specification, design documents, and C++ implementations were developed with the assistance of ChatGPT.