#!/usr/bin/env python # coding: utf-8 # (lecture02:numpy)= # # Numerical Python # # The ability to do basic things with numerical arrays (vectors and matrices) is extremely important in data science applications. # We do numerical algebra in Python using the [Numpy](https://numpy.org/). # Numpy is a **huge** Python library and it has a lot of details. # We are going to cover the very basics here. # When there is something specific that you want to do, the best way to figure out how to do it is to Google it. # # First, let's import ``numpy``. # We typically, do it by creating a shortcut called ``np``: # In[1]: import numpy as np # In this way you can access whatever is in ``numpy`` by going throuh ``np`` which is less characters. # Let's create a 1D numpy array from a list: # In[2]: a = np.array([1.2, 2.0, 3.0, -1.0, 2.0]) print(a) # This behaves just like a vector in Matlab. # You can multiply with a number: # In[3]: 2.0 * a # In[4]: a * 3 # You can add another vector (of the same size): # In[5]: b = np.array([1, 2, 3, 4, 5]) c = a + b c # You can raise all elements to a power: # In[6]: a ** 3 # Or you can apply a standard function to all elements: # In[7]: np.exp(a) # In[8]: np.cos(a) # In[9]: np.sin(a) # In[10]: np.tan(a) # Notice that the functions you can use are in ``np``. # Here is how you can get how many elements you have in the array: # In[11]: a.shape # Also, to see if this is a 1D array (higher dimensional arrays, 2D, 3D, etc. are also possible), you can use this: # In[12]: a.ndim # You access the elements of the array just like the elements of a list: # In[13]: a[0] # In[14]: a[1] # In[15]: a[2:4] # In[16]: a[::2] # In[17]: a[::-1] # You can find the minimum or the maximum of the array like this: # In[18]: a.min() # In[19]: a.max() # So, notice that ``a`` is an object of a class. # The class is called ``np.ndarray``: # In[20]: type(a) # and ``min()`` and ``max()`` are functions of the ``np.ndarray`` class. # Another function of the class is the dot product: # In[21]: a.dot(b) # There is also a submodule called ``numpy.linalg`` which has some linear algebra functions you can apply to arrays. # For 1D arrays (aka vectors) the vector norm is a useful one: # In[22]: np.linalg.norm(a) # In[23]: help(np.linalg.norm) # ## Questions # Consider the two vectors: # In[ ]: r1 = np.array([1.0, -2.0, 3.0]) r2 = np.array([2.0, 2.0, -3.0]) # Use numpy functionality to: # + Find a unit vector in the direction of ``r1``: # In[ ]: # Your code here # + Find the angle between ``r1`` and ``r2`` in radians: # In[ ]: # Your code here # + The projection of ``r2`` on ``r1``: # In[ ]: # Your code here # + Use [numpy.cross](https://numpy.org/doc/stable/reference/generated/numpy.cross.html) to find the cross product between ``r2`` and ``r1``. Then, verify numerically (using numpy functionality) that $\vec{r}_1\cdot\left(\vec{r}_1\times\vec{r}_2\right) = 0$. # In[ ]: # Your code here #