Assuming we have vector A with elements (A1, A2, A3) and vector B with elements (B1, B2, B3), we can calculate the cross product of these two vectors as:
Cross Product = [(A2*B3) – (A3*B2), (A3*B1) – (A1*B3), (A1*B2) – (A2*B1)]
For example, suppose we have the following vectors:
- Vector A: (1, 2, 3)
- Vector B: (4, 5, 6)
We could calculate the cross product of these vectors as:
- Cross Product = [(A2*B3) – (A3*B2), (A3*B1) – (A1*B3), (A1*B2) – (A2*B1)]
- Cross Product = [(2*6) – (3*5), (3*4) – (1*6), (1*5) – (2*4)]
- Cross Product = (-3, 6, -3)
You can use one of the following two methods to calculate the cross product of two vectors in Python:
Method 1: Use cross() function from NumPy
import numpy as np #calculate cross product of vectors A and B np.cross(A, B)
Method 2: Define your own function
#define function to calculate cross product def cross_prod(a, b): result = [a[1]*b[2] - a[2]*b[1], a[2]*b[0] - a[0]*b[2], a[0]*b[1] - a[1]*b[0]] return result #calculate cross product cross_prod(A, B)
The following examples show how to use each method in practice.
Example 1: Use cross() function from NumPy
The following code shows how to use the cross() function from NumPy to calculate the cross product between two vectors:
import numpy as np #define vectors A = np.array([1, 2, 3]) B = np.array([4, 5, 6]) #calculate cross product of vectors A and B np.cross(A, B) [-3, 6, -3]
The cross product turns out to be (-3, 6, -3).
This matches the cross product that we calculated earlier by hand.
Example 2: Define your own function
The following code shows how to define your own function to calculate the cross product between two vectors:
#define function to calculate cross product def cross_prod(a, b): result = [a[1]*b[2] - a[2]*b[1], a[2]*b[0] - a[0]*b[2], a[0]*b[1] - a[1]*b[0]] return result #define vectors A = np.array([1, 2, 3]) B = np.array([4, 5, 6]) #calculate cross product cross_prod(A, B) [-3, 6, -3]
The cross product turns out to be (-3, 6, -3).
This matches the cross product that we calculated in the previous example.
Additional Resources
The following tutorials explain how to perform other common tasks in Python:
How to Calculate Dot Product Using NumPy
How to Normalize a NumPy Matrix
How to Add Row to Matrix in NumPy