OKPEDIA PYTHON VECTOR

How to calculate the cross product in Python

To calculate the cross product between two vectors in the python language use the cross() function in the numpy module.

numpy.cross(v1,v2)

Arguments v1 and v2 are two arrays.

The function returns the cross product v1 x v2.

What is the cross product? The cross product is a vector v1 × v2 which has the null modulus (zero length) when the two vectors v1 and v2 have the same direction.

Example

Import the NumPy library

import numpy as np

Definire due vettori (array).

a = np.array([1,2,3], float)
b = np.array([4,5,6], float)

Use the cross() function to calculate the cross product

np.cross(a,b)

The result is the cross product a × b

array([-3., 6., -3.])

The cross product a × b is a vector orthogonal to both the vector v1 and the vector v2.

Example 2

Define two vectors with the same direction

a = np.array([2,0,0], float)
b = np.array([4,0,0], float)

Calculate the cross product

np.cross(a,b)

In this case the cross product a × b is a null vector because they have the same direction

array([0., 0., 0.])

https://how.okpedia.org/en/python/how-to-calculate-the-cross-product-in-python


Report an error or share a suggestion to enhance this page


Python


FacebookTwitterLinkedinLinkedin