#include #include /*************************************************** * Geometric series * * A finite geometric series has the form * * a + ar + ar^2 + ar^3 + ... + ar^n. * * Here, * * a * * is a scalar multiple and * * r * * is the common ratio. * * Write a function that calculates this sum. * * The function will have three parameters: * * - r, the common ratio; * - n, the largest exponent; and * - a, the scalar multiple. * * We will give a the default argument 1.0. Thus, * * geometric_sum( 0.5, 3 ) * * calculates * * 1 + 0.5 + 0.25 + 0.125, * * while * * geometric_sum( 0.5, 3, 2.0 ) * * calculates * * 2 + 1 + 0.5 + 0.25. * * Notice that a parameter with a default argument * must come after the parameters without default * arguments. * * Also notice that r, n, and a are all declared * const. There is no reason for this function to * change any of these parameters. ***************************************************/ // Function declarations int main(); double geometric_sum( double const r, unsigned int const n, double const a = 1.0 ); // Function definitions int main() { std::cout << geometric_sum( 0.5, 3 ) << std::endl; std::cout << geometric_sum( 0.5, 3, 2.0 ) << std::endl; std::cout << geometric_sum( 2.0, 4 ) << std::endl; std::cout << geometric_sum( 2.0, 4, 3.0 ) << std::endl; return 0; } double geometric_sum( double const r, unsigned int const n, double const a ) { return 0.0; } // Hint: // // Do not calculate each power of r independently. // // Instead, start with // // term = a // // and, after adding each term to the sum, calculate // the next term by multiplying the current term // by r. // // For example, if // // a = 2 // r = 0.5 // // the successive terms are // // 2 // 1 // 0.5 // 0.25 // ... // // Each term is obtained from the preceding term by // multiplying by r. // One solution: /* double geometric_sum( double const r, unsigned int const n, double const a ) { double sum{ 0.0 }; double term{ a }; for ( unsigned int k{ 0 }; k <= n; ++k ) { sum += term; term *= r; } return sum; } */ /*************************************************** * There is also a formula * * If r != 1, then * * 1 - r^(n + 1) * sum = a ---------------------. * 1 - r * * If r == 1, then every term is a, and therefore * * sum = a(n + 1). * * The purpose of this exercise, however, is to * practise loops, constant parameters, and default * arguments rather than simply applying this * formula. ***************************************************/