在Python的线性代数中将方阵提高到 n 次方
要将方阵提高到 n 次方,在线性代数中可以使用numpy. linalg. matrix_power() 函数。对于正整数 n,通过重复矩阵平方和矩阵乘法来计算幂。如果 n == 0
,返回与 M 相同形状的单位矩阵。如果 n < 0,计算其逆矩阵然后提高到 abs(n) 次方。
返回值形状和类型与 M 相同;如果指数为正数或零,则元素的类型与 M 相同。如果指数为负数,元素为浮点数。第一个参数 a 是要“提高幂”的矩阵。第二个参数 n 是指数,可以是任何整数或长整数,可以是正数、负数或零。
步骤
首先,导入所需的库-
import numpy as np
from numpy.linalg import matrix_power
创建一个二维数组,矩阵等同于虚数单位-
arr = np.array([[0, 1], [-1, 0]])
显示数组 –
print("Our Array...\n",arr)
检查尺寸 −
print("\nDimensions of our Array...\n",arr.ndim)
获取数据类型。
print("\nDatatype of our Array object...\n",arr.dtype)
获取形状 –
print("\nShape of our Array object...\n",arr.shape)
将一个方阵提升至n次幂的方法,在线性代数中,使用numpy.linalg.matrix_power()函数来实现。对于正整数n,计算方式是通过多次矩阵的平方和矩阵的乘法来实现的。如果n等于0,则返回与矩阵M相同形状的单位矩阵。如果n小于0,先计算矩阵的逆,然后将其提升至 abs(n)次幂。
print("\nResult...\n",matrix_power(arr, 0))
示例
import numpy as np
from numpy.linalg import matrix_power
# Create a 2D array, matrix equivalent of the imaginary unit
arr = np.array([[0, 1], [-1, 0]])
# Display the array
print("Our Array...\n",arr)
# Check the Dimensions
print("\nDimensions of our Array...\n",arr.ndim)
# Get the Datatype
print("\nDatatype of our Array object...\n",arr.dtype)
# Get the Shape
print("\nShape of our Array object...\n",arr.shape)
# To raise a square matrix to the power n in Linear Algebra, use the numpy.linalg.matrix_power() in Python
print("\nResult...\n",matrix_power(arr, 0))
输出
Our Array...
[[ 0 1]
[-1 0]]
Dimensions of our Array...
2
Datatype of our Array object...
int64
Shape of our Array object...
(2, 2)
Result...
[[1 0]
[0 1]]