在Python中,你可以使用列表(list)来表示向量。下面是一个简单的`Vector`类的定义,它支持向量的基本运算,如加法、减法、点乘和标量乘法:
from math import sqrt
class Vector:
def __init__(self, x):
定义向量:Vector(x),其中x是一个列表
self.x = tuple(x)
def __str__(self):
让print的时候显示Vector([x1,x2,x3,...])
return 'Vector({})'.format(list(self.x))
def __add__(self, other):
向量加法
z = list(map(lambda x, y: x + y, self.x, other.x))
return Vector(z)
def __sub__(self, other):
向量减法
z = list(map(lambda x, y: x - y, self.x, other.x))
return Vector(z)
def dot(self, other):
计算向量点乘
z = sum(list(map(lambda x, y: x * y, self.x, other.x)))
return z
def __mul__(self, scalar):
定义向量乘以标量
z = list(map(lambda x: x * scalar, self.x))
return Vector(z)
def __rmul__(self, scalar):
定义向量乘以标量(标量在左边)
return self.__mul__(scalar)
使用这个类,你可以创建向量对象,并执行向量运算,例如:
创建两个向量实例
v1 = Vector([1, 2, 3])
v2 = Vector([4, 5, 6])
向量加法
v3 = v1 + v2
print(v3) 输出:Vector([5, 7, 9])
向量点乘
dot_product = v1.dot(v2)
print(dot_product) 输出:32
向量乘以标量
v4 = v1 * 2
print(v4) 输出:Vector([2, 4, 6])
如果你需要处理更高维度的向量,可以使用`numpy`库,它提供了更强大和高效的数组操作和数学函数。
import numpy as np
使用numpy创建一个3x1的列向量
v = np.array([, , ])
print(v) 输出:
array([,
,
])
使用`numpy`,你可以进行更复杂的向量运算,如矩阵乘法、向量的模长计算等。