
上QQ阅读APP看书,第一时间看更新
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:
- Square the coordinates, obtaining an array that contains (x**2, y**2) elements.
- Sum those with numpy.sum over the last axis.
- 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]