I'm going to begin by initializing a numpy array.
import numpy as np x = np.array([4,2,9,-6,5,11,13]) x
array([ 4, 2, 9, -6, 5, 11, 13])
So now I have instantiated a numpy. And I may want to figure out the highest and/or lowest elements in the array. Now numpy has built in functions for precisely this.
np.max(x)
13
x.max()
np.min(x)
-6
x.min()
So I'm going to go ahead and type in np.random.random once more and feed it in a size. I want to make random 2 by 1 numpy array. This produces a 2 by 1 matrix with elements drawn randomly from the uniform distribution.
np.random.random([2,1])
array([[0.89333437], [0.80202254]])
I can also produce one element at random by simply typing np.random.random.
np.random.random()
0.9087695743413609
I'll have a number drawn randomly from the uniform distribution, in this case, 0.977
is numpy's built in linear algebra module. And I can access it via np, or numpy, dot linalg. Just as with random, there is a vast set of methods and attributes within. And in particular, I want to talk about finding the norm of a matrix
norm is built into numpy's linear algebra module as well. Now let's recall our numpy array x. I now want to find its L2 norm. That is the square root of the sum of each of its elements squared.
The way to do this is np.linalg.norm(x)
np.linalg.norm(x)
21.2602916254693
Write a function called norm that takes as input two Numpy column arrays A and B, adds them, and returns s, the L2 norm of their sum.
def norm(A,B): """ Takes two Numpy column arrays, A and B, and returns the L2 norm of their sum. Arg: A - a Numpy array B - a Numpy array Returns: s - the L2 norm of A+B. """ s = np.linalg.norm(A + B) return s
A = np.random.random([4,]) B = np.random.random([4,])
A
array([0.12531355, 0.43334018, 0.70309934, 0.10365833])
B
array([0.99766888, 0.94448308, 0.77763883, 0.76006777])
norm(A,B)
2.469432075981698