import numpy as np import numpy.linalg as la import matplotlib.pyplot as pt
Here's a matrix of which we're trying to compute the norm:
n = 2 A = np.random.randn(n, n) A
array([[-0.12603194, 0.74240991], [ 0.07209953, -0.91593647]])
where the vector norm must be specified, and the value of the matrix norm $\|A\|$ depends on the choice of vector norm.
For instance, for the $p$-norms, we often write:
and similarly for different values of $p$.
We can approximate this by just producing very many random vectors and evaluating the formula:
xs = np.random.randn(n, 1000)
First, we need to bring all those vectors to have norm 1. First, compute the norms:
p = 2 norm_xs = np.sum(np.abs(xs)**p, axis=0)**(1/p) norm_xs.shape
Then, divide by the norms and assign to
Then check the norm of a randomly chosen vector.
normalized_xs = xs/norm_xs la.norm(normalized_xs[:, 316], p)
Let's take a look:
pt.plot(normalized_xs, normalized_xs, "o") pt.gca().set_aspect("equal")
Now apply $A$ to these normalized vectors:
A_nxs = A.dot(normalized_xs)
Let's take a look again:
pt.plot(normalized_xs, normalized_xs, "o", label="x") pt.plot(A_nxs, A_nxs, "o", label="Ax") pt.legend() pt.gca().set_aspect("equal")
Next, compute norms of the $Ax$ vectors:
norm_Axs = np.sum(np.abs(A_nxs)**p, axis=0)**(1/p) norm_Axs.shape
What's the biggest one?
Compare that with what
numpy thinks the matrix norm is: