Calculating the norm

We can review the basic concepts illustrated in this section by calculating the norm of a set of coordinates. For a two-dimensional vector, the norm is defined as follows:

    norm = sqrt(x**2 + y**2) 

Given an array of 10 coordinates (x, y), we want to find the norm of each coordinate. We can calculate the norm by taking these steps:

  1. Square the coordinates, obtaining an array that contains (x**2, y**2) elements.
  2. Sum those with numpy.sum over the last axis.
  3. Take the square root, element-wise, with numpy.sqrt.

The final expression can be compressed in a single line:

    r_i = np.random.rand(10, 2) 
norm = np.sqrt((r_i ** 2).sum(axis=1))
print(norm)
# Output:
# [ 0.7314 0.9050 0.5063 0.2553 0.0778 0.9143 1.3245
0.9486 1.010 1.0212]
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.149.29.71