The root mean square is a value used in statistics, physics, electronics, and numerous other fields. We approach it as just another problem involving formulas, arrays, functions, and data input. The formula is as follows:
Translating the root mean square to C++.
The root mean square (RMS) example further demonstrates the conversion of the summation operator, Σ, to C++ code. Sometimes, the operator includes additional information about the problem. Although the information may make the formula look increasingly formidable, we can easily incorporate it into the C++ code. The conversion's "key" is recognizing that xi is a sequence of real numbers - an array of float or double C++ variables.
Two equivalent versions of the RMS formula as it might appear in a textbook or problem statement. The second version highlights the solution's steps:
Square each number.
Add the squares together.
Divide the sum by n (i.e., the number of numbers in the sequence).
Calculate the square root of the quotient.
The picture illustrates how parts of the summation notation map to the elements of a C++ for-loop.
xi → x[i]
xi2 → pow(x[i], 2)
Σ xi2 → sum += pow(x[i], 2)
i = 0 and n - 1 → for (i = 0; i < n; ...)
The RMS Function
The for-loop presented in the previous figure is the central part of the RMS function. Adding a function header, a variable definition and initialization, and a return statement completes the function.
RMS Program
To complete the program, we add variable definitions, input and output operations, a call to the rms function, and some miscellaneous syntax. Unlike previous examples, this program can process all real numbers, including -1, implying that we must devise another data input technique. The program prompts the user to continue entering data or end input and complete the calculation. While this approach is somewhat cumbersome, it allows us to explore the get and ignore functions.