← back

Compute the Cross Product of Two 3D Vectors

#118 · Linear Algebra · Easy

⊣ Solve on deep-ml.com

Problem

Compute the cross product of two 3D vectors. The cross product produces a vector perpendicular to both input vectors with magnitude equal to the area of the parallelogram they span.

Solution

1
2
3
4
5
def cross_product(v1: list[float], v2: list[float]) -> list[float]:
    x = v1[1] * v2[2] - v1[2] * v2[1]
    y = v1[2] * v2[0] - v1[0] * v2[2]
    z = v1[0] * v2[1] - v1[1] * v2[0]
    return [x, y, z]

Explanation

  1. Given vectors a = (a1, a2, a3) and b = (b1, b2, b3), the cross product is:
  2. - x-component: a2*b3 - a3*b2
  3. - y-component: a3*b1 - a1*b3
  4. - z-component: a1*b2 - a2*b1
  5. This can be remembered as the determinant of a 3x3 matrix with unit vectors i, j, k in the first row.
  6. Properties: The result is perpendicular to both inputs, its magnitude equals |a||b|sin(theta), and it follows the right-hand rule.
  7. If the vectors are parallel, the cross product is the zero vector.

Complexity

  • Time: O(1) -- fixed number of arithmetic operations
  • Space: O(1)