如何在 NumPy 中获取向量的大小?
线性代数的基本特征是向量,它们是具有方向和大小的对象。在Python中,NumPy 数组可用于描述向量。
获取向量的大小主要有两种方式:
- 通过定义一个显式函数,该函数根据以下数学公式计算给定向量的大小:
if V is vector such that, V = (a, b, c) then ||V|| = ?(a*a + b*b + c*c)
以下是一些按照上述方法计算向量大小的程序:
# program to compute magnitude of a vector # importing required libraries import numpy import math # function defination to compute magnitude o f the vector def magnitude(vector): return math.sqrt(sum(pow(element, 2) for element in vector)) # displaying the original vector v = numpy.array([0, 1, 2, 3, 4]) print('Vector:', v) # computing and displaying the magnitude of the vector print('Magnitude of the Vector:', magnitude(v))
输出:
Vector: [0 1 2 3 4] Magnitude of the Vector: 5.477225575051661
以下是使用相同方法的另一个示例:
# program to compute magnitude of a vector # importing required libraries import numpy import math # function defination to compute magnitude o f the vector def magnitude(vector): return math.sqrt(sum(pow(element, 2) for element in vector)) # computing and displaying the magnitude of the vector print('Magnitude of the Vector:', magnitude(numpy.array([1, 2, 3])))
输出:
Magnitude of the Vector: 3.7416573867739413
- 通过使用
NumPy
库的linalg
模块中的norm()
方法。NumPy
的线性代数模块提供了在任何NumPy
数组上应用线性代数的各种方法。下面是一些使用numpy.linalg.norm()
计算向量大小的程序:# program to compute magnitude of a vector # importing required libraries import numpy # displaying the original vector v = numpy.array([1, 2, 3]) print('Vector:', v) # computing and displaying the magnitude of # the vector using norm() method print('Magnitude of the Vector:', numpy.linalg.norm(v))
输出:
Vector: [1 2 3] Magnitude of the Vector: 3.7416573867739413
额外的参数
ord
可用于计算向量的norm()
的第 n 阶。# program to compute the nth order of the # magnitude of a vector # importing required libraries import numpy # displaying the original vector v = numpy.array([0, 1, 2, 3, 4]) print('Vector:', v) # computing and displaying the magnitude of the vector print('Magnitude of the Vector:', numpy.linalg.norm(v)) # Computing the nth order of the magnitude of vector print('ord is 0: ', numpy.linalg.norm(v, ord = 0)) print('ord is 1: ', numpy.linalg.norm(v, ord = 1)) print('ord is 2: ', numpy.linalg.norm(v, ord = 2)) print('ord is 3: ', numpy.linalg.norm(v, ord = 3)) print('ord is 4: ', numpy.linalg.norm(v, ord = 4))
输出:
Vector: [0 1 2 3 4] Magnitude of the Vector: 5.477225575051661 ord is 0: 4.0 ord is 1: 10.0 ord is 2: 5.477225575051661 ord is 3: 4.641588833612778 ord is 4: 4.337613136533361