Week 6

Vectors

Exercise 6.1

Write a function named norm that returns the Euclidean norm of a vector $\vec{v} \in \mathbb{R}^n$.

Recall that if $$ \vec{v} = \begin{bmatrix} v_1 \\ v_2 \\ \vdots \\ v_n \end{bmatrix}, $$ then the Euclidean norm of $\vec{v}$ is $$ \lVert \vec{v} \rVert = \sqrt{v_1^2 + v_2^2 + \cdots + v_n^2}\,. $$

For example, the function call norm({1, 1}) should return 1.41421 and norm({0.3, 0.4}) should return 0.5. The function should work for vectors of any dimension; for instance, norm({1, 1, 1, 1}) should return 2.

Solution

Here is one possible solution.

double norm(const vector<double>& v) {
    double s = 0;

    for (int i = 0; i < v.size(); ++i) {
        s += v[i] * v[i];
    }

    return sqrt(s);
}

Note that #include <cmath> is needed for the sqrt function.

Remark: It is preferable to write vector<double>::size_type i instead of int i since the former is an unsigned integral type meant for holding the size of a vector<double>. In fact, the return type of v.size is also vector<double>::size_type.

Alternative solution

Here is another possible solution, using a range-based for loop.

double norm(const vector<double>& v) {
    double s = 0;

    for (const double& x : v) {
        s += x * x;
    }

    return sqrt(s);
}

Exercise 6.2

Write a function named inner_product that returns the Euclidean inner product of two vectors $\vec{v}, \vec{w} \in \mathbb{R}^n$.

Recall that if $$ \vec{v} = \begin{bmatrix} v_1 \\ v_2 \\ \vdots \\ v_n \end{bmatrix}, \quad \vec{w} = \begin{bmatrix} w_1 \\ w_2 \\ \vdots \\ w_n \end{bmatrix}, $$ then the Euclidean inner product of $\vec{v}$ and $\vec{w}$ is $$ \langle \vec{v}, \vec{w} \rangle = v_1 w_1 + v_2 w_2 + \cdots + v_n w_n. $$

For example, the function call inner_product({1, 0}, {0, 1}) should return 0 and inner_product({1, -1}, {-2, 2}) should return -4. The function should work for vectors of any dimension; for instance, inner_product({0.1, -0.1, 0.1}, {0, 1, 0}) should return -0.1.

Solution

Here is one possible solution.

double inner_product(const vector<double>& v, const vector<double>& w) {
    double p = 0;

    for (int i = 0; i < v.size(); ++i) {
        p += v[i] * w[i];
    }

    return p;
}

See also the remark in the solution to Exercise 6.1.