python线性代数向量

时间:2021-09-21 20:09:11

python线性代数向量

##-----两个向量的相加
def vector_add(v, w):
"""adds corresponding elements"""
return [v_i + w_i
for v_i, w_i in zip(v, w)]

##-----两个向量相减
def vector_subtract(v, w):
"""subtracts corresponding elements"""
return [v_i - w_i
for v_i, w_i in zip(v, w)]


##-----多个向量相加
def vector_sum(vectors):
"""sums all corresponding elements"""
result = vectors[0] # 从第一个向量开始
for vector in vectors[1:]: # 之后遍历其他向量
result = vector_add(result, vector) # 最后计入总和
return result
##或者
def vector_sum(vectors):
return reduce(vector_add, vectors)


##------向量乘以标量

def scalar_multiply(c, v):
"""c is a number, v is a vector"""
return [c * v_i for v_i in v]


##------一系列向量(长度相同)的均值
def vector_mean(vectors):
"""compute the vector whose ith element is the mean of the
ith elements of the input vectors"""
n = len(vectors)
return scalar_multiply(1/n, vector_sum(vectors))

##-----向量的点乘
def dot(v, w):
"""v_1 * w_1 + ... + v_n * w_n"""
return sum(v_i * w_i
for v_i, w_i in zip(v, w))

##----向量的平方
def sum_of_squares(v):
"""v_1 * v_1 + ... + v_n * v_n"""
return dot(v, v)


###
import math

def magnitude(v):
return math.sqrt(sum_of_squares(v)) # math.sqrt是平方根函数


def squared_distance(v, w):
"""(v_1 - w_1) ** 2 + ... + (v_n - w_n) ** 2"""
return sum_of_squares(vector_subtract(v, w))

def distance(v, w):
return math.sqrt(squared_distance(v, w))
empty