# Working with vectors in Python¶

Working with vectors in Python is made simple by using numpy arrays.

import numpy as np

# define two 2D vectors using numpy arrays
a = np.array([5,1])
b = np.array([2,4])
print(a)

[5 1]

print(b)

[2 4]

# vector addition
c = a + b
print(c)

[7 5]

# vector subtraction
d = a - b
print(d)

[ 3 -3]


Remember that multiplication of numpy arrays involves element-wise multiplication and returns a new array.

# vector multiplication?
e = a * b
print(e)

[10  4]


This is not the same as $$\mathbf{a}\cdot\mathbf{b}$$ (dot product) or $$\mathbf{a}\times\mathbf{b}$$ (cross product). Instead we can use the numpy.dot() and numpy.cross() functions to compute the dot product and cross product of $$\mathbf{a}$$ and $$\mathbf{b}$$ respectively:

# dot product
dot = np.dot(a,b)
print(dot)

14

# cross product
cross = np.cross(a,b)
print(cross)

18


You might have noticed that the dot product is equal to the sum of a*b:

print(a*b)

[10  4]

print(np.sum(a*b))

14

print(np.dot(a,b))

14


Which should make sense from the definition of the cross product.

## Exercise¶

You previously wrote some code to calculate the interatomic distances (and angles) between pairs of atoms in two molecules, using the expression

$r_{ij} = \sqrt{(x_i-x_j)^2 + (y_i-y_j)^2 + (z_i-z_j)^2}$

Starting from your previous code, or from scratch, write a new version of this code that solves the same problem using numpy arrays and np.dot().