P2.7.3Vector products
Write two functions which, given two lists of length 3 representing three-dimensional vectors \(\mathbf{a}\) and \(\mathbf{b}\), calculate the dot product, \(\mathbf{a}\cdot\mathbf{b}\) and the vector (cross) product, \(\mathbf{a}\times\mathbf{b}\).
Write two more functions to return the scalar triple product, \(\mathbf{a}\cdot(\mathbf{b}\times\mathbf{c})\) and the vector triple product, \(\mathbf{a}\times(\mathbf{b}\times\mathbf{c})\).
Show solution
The following code implements and tests the four required functions. Note that the second pair use the first pair and the use of zip to calculate the dot product.
def dot(a, b):
""" Return the dot product of vectors a, b. """
return sum(ai * bi for ai, bi in zip(a, b))
def cross(a, b):
""" Return the vector (cross) product of vectors a, b. """
return [a[1]*b[2] - a[2]*b[1],
a[2]*b[0] - a[0]*b[2],
a[0]*b[1] - a[1]*b[0]]
def scalar3(a, b, c):
""" Return the scalar triple product of vectors a, b, c. """
return dot(a, cross(b, c))
def vector3(a, b, c):
""" Return the vector triple product of vectors a, b, c. """
return cross(a, cross(b, c))
a, b, c = [1, -2, 1], [2, -0.5, -1], [0.5, 1, -1.5]
print('a . b =', dot(a, b))
print('a x b =', cross(a, b))
print('a . (b x c) =', scalar3(a, b, c))
print('a x (b x c) =', vector3(a, b, c))
The output is:
a . b = 2.0
a x b = [2.5, 3, 3.5]
a . (b x c) = -1.0
a x (b x c) = [-7.0, -0.5, 6.0]