Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Return the cross product of two (arrays of) vectors in Python
The cross product of two vectors produces a third vector perpendicular to both input vectors. In Python, we use numpy.cross() to compute the cross product of two (arrays of) vectors.
Syntax
numpy.cross(a, b, axisa=-1, axisb=-1, axisc=-1, axis=None)
Parameters
The numpy.cross() method accepts the following parameters:
- a - Components of the first vector(s)
- b - Components of the second vector(s)
- axisa - Axis of a that defines the vector(s). Default is the last axis
- axisb - Axis of b that defines the vector(s). Default is the last axis
- axisc - Axis of c containing the cross product vector(s). Default is the last axis
- axis - If defined, overrides axisa, axisb and axisc
Basic Cross Product Example
Let's compute the cross product of two 3D vectors ?
import numpy as np
# Creating two vectors
arr1 = [13, 11, 19]
arr2 = [19, 10, 8]
# Display the vectors
print("Vector 1:", arr1)
print("Vector 2:", arr2)
# Compute the cross product
result = np.cross(arr1, arr2)
print("Cross Product:", result)
Vector 1: [13, 11, 19] Vector 2: [19, 10, 8] Cross Product: [-102 257 -79]
Cross Product of 2D Vectors
For 2D vectors, the cross product returns a scalar value ?
import numpy as np
# 2D vectors
vec1 = [3, 4]
vec2 = [2, 5]
# Cross product of 2D vectors returns a scalar
result = np.cross(vec1, vec2)
print("2D Cross Product:", result)
print("Type:", type(result))
2D Cross Product: 7 Type: <class 'numpy.int64'>
Cross Product of Multiple Vector Pairs
You can compute cross products of multiple vector pairs simultaneously ?
import numpy as np
# Multiple 3D vectors
vectors_a = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]])
vectors_b = np.array([[0, 1, 0], [0, 0, 1], [1, 0, 0]])
# Cross product of multiple vector pairs
result = np.cross(vectors_a, vectors_b)
print("Multiple Cross Products:")
print(result)
Multiple Cross Products: [[ 0 0 1] [ 1 0 0] [ 0 1 0]]
Key Properties
| Property | Description | Example |
|---|---|---|
| Anti-commutative | a × b = -(b × a) | [1,0,0] × [0,1,0] = [0,0,1] |
| Perpendicular | Result is perpendicular to both inputs | Dot product with inputs = 0 |
| 2D Result | Returns scalar for 2D vectors | Magnitude of z-component |
Conclusion
Use numpy.cross() to compute cross products of vectors in Python. For 3D vectors, it returns a perpendicular vector, while for 2D vectors, it returns a scalar representing the z-component magnitude.
Advertisements
