Tutorial

How to Find Python Cross Product?

8 min read
How to do cross product in Python

Learn ways to perform Python cross product with/without NumPy module. Find its usage in vector math & geometry with code examples in Python.

Introduction

Cross product is a fundamental vector operation that plays a vital role in mathematics, geometry, and various real-world applications.

It provides a means to obtain a new vector that is orthogonal to (at right angles to) two given vectors.

It has important applications in physics, engineering, and computer graphics.

What are Vectors and cross-products?

In mathematics, a vector has both magnitude and direction.

The cross product of two non-parallel vectors results in a third vector that is perpendicular to the plane containing the two input vectors.

In simple terms, the cross product is a mathematical operation that takes two vectors and spits out a new vector that is perpendicular to both of the input vectors.

The cross-product is useful for:

  • finding surface normals (vectors at right angles to a surface),
  • calculating torque and angular momentum,
  • determining the orientation of a rigid body, and
  • computing areas of parallelograms formed by vectors.

Therefore, it is an essential operation for 3D math and physics computations.

Calculating and formula of cross-product

The vectors \bf{A} and \bf{B} are lying in 3D, so must be in the form:

  • \textbf{A} = a_1\textbf{i}+a_2\textbf{j}+a_3\textbf{k}
  • \textbf{B} = b_1\textbf{i}+b_2\textbf{j}+b_3\textbf{k}

Then, if we represent the cross product in determinant form, we have the folllowing expression:
\textbf{A} \times \textbf{B}=\begin{vmatrix} \textbf{i} & \textbf{j} & \textbf{k}\\ a_1 & a_2 & a_3\\ b_1 & b_2 & b_3 \end{vmatrix}
Then, making use of cofactor expansion, we can get a formula for the cross product:
\textbf{A} \times \textbf{B}=\begin{vmatrix} a_2 & a_3\\ b_2 & b_3 \end{vmatrix} \textbf{i} -\begin{vmatrix} a_1 & a_3\\ b_1 & b_3 \end{vmatrix} \textbf{j} +\begin{vmatrix} a_1 & a_2\\ b_1 & b_2 \end{vmatrix} \textbf{k}
=(a_2b_3-a_3b_2)\textbf{i}-(a_1b_3-a_3b_1)\textbf{j}+(a_1b_2-a_2b_1)\textbf{k}

This formula gives the components of the resulting vector directly.

If we need to know the magnitude, or norm, of the cross product, we use the formula:

\Vert \textbf{A} \times \textbf{B}\Vert=\Vert \textbf{A}\Vert \Vert \textbf{B}\Vert sin(\theta)

where

  • \Vert \bf{A}\Vert and \Vert \bf{B}\Vert are the magnitudes (or, norms) of the vectors \bf{A} and \bf{B} respectively.
  • \theta is the angle between vectors \bf{A} and \bf{B}, and
  • \Vert \textbf{A} \times \textbf{B}\Vert is the norm of the cross product \textbf{A} \times \textbf{B}.

Below, we can see these relationships diagrammatically:

python cross product of two values

 

As can be seen from the diagram, the cross product of two vectors gives a resulting vector that is perpendicular to the plane formed by the original vectors.

Implementing Python Cross Product

It’s time to write some Python code! We can make use of lists, tuples, or arrays to represent vectors in Python. However, to calculate the cross-product, the two vectors must have dimension 3. That is, both of the vectors must have three values; one for each of the unit vector components \textbf{i}, \textbf{j}, and \textbf{k}.

So, in this article, we want to explore two ways we can carry out calculations involving the cross product: doing it ourselves vs. using the numpy library.

Manual implementation of cross product in Python

We can calculate the cross product manually using the determinant of a matrix formed by the vectors.

This method is particularly useful when you want to understand the underlying mathematical principles.

def cross_product(a, b):
    # unpack the vectors to make it easy to understand
    # the implementation
    a1, a2, a3 = a
    b1, b2, b3 = b

    # Calculate the x, y, and z components for the
    # cross product vector
    x = a2 * b3 - a3 * b2
    y = a3 * b1 - a1 * b3
    z = a1 * b2 - a2 * b1

    return (x, y, z)  # Return the result as a tuple

# Test function
a = (2, -5, 1)
b = (3, -2, -4)
c = cross_product(a, b)
print(c)

u = (1, 2, 3)
v = (4, 5, 6)
w = cross_product(u, v)
print(w)

In this calculation, our vectors are represented as tuples.

Our manual implementation made use of the formula introduced in the previous section (the one derived from the determinant calculation).

The output produced is as follows:
output for manual implementation of cross product
In the next section, we will make use of a ready-made cross-product function provided by NumPy.

Using NumPy to find cross product in Python

If we do not want to implement the cross-product calculation ourselves, there is another way.

We can make use of NumPy’s predefined function, np.cross, to compute the cross product of two vectors.

See the below example of how to use the np.cross function.

import numpy as np

a = np.array((2, -5, 1))
b = np.array((3, -2, -4))
c = np.cross(a, b)
print(c)

u = np.array((1, 2, 3))
v = np.array((4, 5, 6))
w = np.cross(u, v)
print(w)

We are making use of the same vector values used in the previous examples, but here represented as NumPy ndarrays.

The function np.cross returns another ndarray representing the cross product of the two input vectors.

Let us see the output produced by this approach:

output for numpy implementation of cross product
The results are the same (just that they are represented differently, that’s all). The NumPy approach made our code shorter, and more concise.

So far, we have been calculating the cross product of two vectors.

What if we had three or more vectors in our product?

We will see how to use a nice Python approach using NumPy’s np.cross to find the cross product of three or more vectors.

Calculating cross product for three or more vectors

Sometimes, you may need to calculate the cross product of more than two vectors. Fortunately, Python provides a straightforward way to handle such scenarios.

To calculate the cross product of multiple vectors in Python, you can use the np.cross function along with the reduce function from the functools module.

The reduce function allows you to apply a specific operation, in this case, the cross product, to a sequence of vectors iteratively.

Here’s an example of how to calculate the cross product of multiple vectors using np.cross and reduce:

import numpy as np
from functools import reduce

# Define a list of vectors
data = [(1, 2, 3), (4, 5, 6), (7, 8, 9), (10, 11, 12)]

# create an ndarray of vectors
vectors = [np.array(vector) for vector in data]

# Calculate the cross product of all the four vectors
product = reduce(np.cross, vectors)

print(product)

In this example, we have an array of vectors vectors containing four vectors.

By applying the reduce function to np.cross and vectors, the cross product is calculated iteratively, resulting in a single cross product vector.

The final cross product is then printed, and the resulting vector we get is:

output for numpy.cross three or more vectors cross product in Python

In the upcoming section, we will further use the NumPy np.cross function to implement a function that computes the area of a parallelogram.

Cross Product in Vector Mathematics and Geometry

Now that we’ve explored various methods of calculating the cross product, let’s take a look at a real-world application of calculating the cross product.

The example we want to explore is finding the area of parallelograms.

Area of Parallelograms with the help of cross product in Python

The cross product is a tool for solving problems related to the area of parallelograms.

The cross product of two vectors can be used to find the area of a parallelogram formed by those vectors.

Let’s see a code example of calculating the area of a parallelogram using the cross product:

import numpy as np

def calculate_parallelogram_area(a, b):
    v1 = np.array(a)
    v2 = np.array(b)

    # Calculate the cross product
    v3 = np.cross(v1, v2)

    # The magnitude of the cross product is the area of the parallelogram
    return np.linalg.norm(v3)

# Test our function: Define two parallelograms, p and q
p1, p2 = (2, -3), (5, 3)    # parallelogram p
q1, q2 = (6, 1), (5, -8)   # parallelogram q

# Find their areas
area_p = calculate_parallelogram_area(p1, p2)
area_q = calculate_parallelogram_area(q1, q2)

# Display the areas
print(f"The area of parallelogram p is {area_p}sq units.")
print(f"The area of parallelogram q is {area_q}sq units.")

In this example, we defined a function, calculate_parallelogram_area, that calculates, and returns, the area of a parallelogram.

The area of a parallelogram is equivalent to the magnitude of the cross product of two vectors.

The calculated areas are shown in the output produced by our script:

output for calculating the area of parallelograms in Python

The cross product is a valuable mathematical concept.

In this article, we explored ways in which we could calculate this quantity.

We discussed both how to do this by implementing our code, and how to use np.cross function without worrying about implementing it ourselves.

Finally, we wrote some code to compute the area of a parallelogram using the cross-product approach.

We have other Python tutorial topics. Feel free to check them out. Also, you can hire a Python tutor if you need to learn Python programming.