numpy.cross()
方法计算两个向量的叉积。
示例
import numpy as np
# create two input arrays
array1 = np.array([1, 2, 3])
array2 = np.array([4, 5, 6])
# compute the cross product of array1 and array2
result = np.cross(array1, array2)
print(result)
# Output:[-3 6 -3]
cross() 语法
numpy.cross()
方法的语法是
numpy.cross(a, b, axisa = -1, axisb = -1, axisc = -1, axis = None)
cross() 参数
numpy.cross()
方法接受以下参数
a
- 第一个输入数组b
- 第二个输入数组axisa
(可选) - 对 a 计算叉积的轴axisb
(可选) - 对 b 计算叉积的轴axisc
(可选) - 对 c 计算叉积的轴axis
(可选) - 如果指定,它将覆盖 axisa、axisb 和 axisc
注意:此处所有可选参数均接受整数值。
cross() 返回值
numpy.cross()
方法返回一个包含 a 和 b 叉积的数组。
示例 1:计算两个数组的叉积
import numpy as np
# create two input arrays
array1 = np.array([1, 2, 3])
array2 = np.array([4, 5, 6])
# compute the cross product of array1 and array2
result = np.cross(array1, array2)
print(result)
输出
[-3 6 -3]
这里,我们有两个输入数组
array1 = [1, 2, 3]
array2 = [4, 5, 6]
现在,为了计算叉积,我们应用以下公式
cross product = (array1[1] * array2[2] - array1[2] * array2[1],
array1[2] * array2[0] - array1[0] * array2[2],
array1[0] * array2[1] - array1[1] * array2[0])
然后,代入输入数组中的值
cross product = (2 * 6 - 3 * 5,
3 * 4 - 1 * 6,
1 * 5 - 2 * 4)
最后,评估表达式后
cross product = (-3, 6, -3)
因此,np.cross(array1, array2)
的输出数组是 [ -3, 6, -3]
。
示例 2:cross() 中 axisa、axisb、axisc 参数的使用
import numpy as np
# create two input arrays
array1 = np.array([[1, 2, 3], [4, 5, 6]])
array2 = np.array([[7, 8, 9], [10, 11, 12]])
# compute the cross product
# along the first axis of each array
resultAxis = np.cross(array1, array2, axisa = 1, axisb = 1, axisc = 1)
print("Result with axisa = 1, axisb = 1, axisc = 1:")
print(resultAxis)
输出
Result with axisa = 1, axisb = 1, axisc = 1: [[-6 12 -6] [-6 12 -6]]
这里,为了沿着轴 1 计算叉积,我们考虑 array1 和 array2 轴 1 上的向量
array1 = ([[1, 2, 3],
[4, 5, 6]])
array2 = ([[7, 8, 9],
[10, 11, 12]])
对于 array1 和 array2 的第一行,叉积计算如下
[1, 2, 3] × [7, 8, 9] = [-6, 12, -6]
类似地,对于 array1 和 array2 的第二行,叉积计算如下
[4, 5, 6] × [10, 11, 12] = [-6, 12, -6]
示例 3:cross() 中 axis 参数的使用
import numpy as np
# create two input arrays
array1 = np.array([[1, 2, 3], [4, 5, 6]])
array2 = np.array([[7, 8, 9], [10, 11, 12]])
# compute the cross product along axis 0
axis0 = np.cross(array1, array2, axis = 0)
print("Result with axis = 0:")
print(axis0)
# compute the cross product along axis 1
axis1 = np.cross(array1, array2, axis = 1)
print("\nResult with axis = 1:")
print(axis1)
输出
Result with axis=0: [-18 -18 -18] Result with axis=1: [[-6 12 -6] [-6 12 -6]]
这里,
axis = 0
- 输出[-18, -18, -18]
表示 array1 和 array2 的列向量上的叉积。axis = 1
- 输出[[ -6, 12, -6], [ -6, 12, -6]]
表示 array1 和 array2 的行向量上的叉积。