#include #include /*************************************************** * Inner product of two vectors * * Write a function that calculates the inner * product, also called the dot product, of two * vectors having the same dimension. ***************************************************/ // Function declarations double inner_product( double const vec1[], double const vec2[], std::size_t const capacity ); int main(); // Function definitions int main() { double u1[4]{ 9.3, -1.2, 4.6, -4.8 }; double u2[4]{ 6.9, 3.8, -2.1, 6.6 }; double v1[10]{ -3.6, -2.8, -9.7, 1.6, -1.1, -8.5, 3.7, 0.0, 2.8, -2.7 }; double v2[10]{ 9.5, 7.2, 9.2, 7.9, -6.2, 8.4, 7.6, -1.7, 7.2, 1.5 }; std::cout << inner_product( u1, u2, 4 ) << " = 18.27" << std::endl; std::cout << inner_product( v1, v2, 10 ) << " = -151.31" << std::endl; return 0; } /*************************************************** * inner_product * * Return the inner product of the two vectors. * * Recall that the inner product, or dot product, * of two n-dimensional vectors is * * n * ----- * \ * ) u_k v_k. * / * ----- * k = 1 * * The mathematical notation used in your linear * algebra course indexes the entries from 1 through * n. In C++, however, an array with capacity n has * indices from 0 through n - 1. ***************************************************/ double inner_product( double const vec1[], double const vec2[], std::size_t const capacity ) { return 0.0; } // Hint: // // This is very similar to the function sum(...) // that you previously wrote. // // In that function, you added each entry of one // array to a running sum. // // Here, you instead add the product of the // corresponding entries of two arrays: // // vec1[0]*vec2[0] // + vec1[1]*vec2[1] // + vec1[2]*vec2[2] // + ... // // You will therefore need a local variable of type // double that stores the running sum. // // What should its initial value be? // One solution: /* double inner_product( double const vec1[], double const vec2[], std::size_t const capacity ) { double result{ 0.0 }; for ( std::size_t k{ 0 }; k < capacity; ++k ) { result += vec1[k]*vec2[k]; } return result; } */