一、代碼倉庫
https://github.com/Chufeng-Jiang/Python-Linear-Algebra-for-Beginner/tree/main
二、向量的基本運(yùn)算
2.1 加法
2.2 數(shù)量乘法
2.3 向量運(yùn)算的基本性質(zhì)
2.4 零向量
2.5 向量的長度
2.6 單位向量
單位向量叫做 u hat
2.7 點(diǎn)乘/內(nèi)積:兩個(gè)向量的乘法 --答案是一個(gè)標(biāo)量
三、手寫Vector代碼
3.1 在控制臺測試__repr__和__str__方法
3.2 創(chuàng)建實(shí)例測試代碼
from playLA.Vector import Vector
if __name__ == "__main__":
vec = Vector([5, 2])
print(vec)
print("len(vec) = {}".format(len(vec)))
print("vec[0] = {}, vec[1] = {}".format(vec[0], vec[1]))
文章來源:http://www.zghlxwxcb.cn/news/detail-717878.html
3.3 完整代碼
文章來源地址http://www.zghlxwxcb.cn/news/detail-717878.html
Vector.py
import math
from ._globals import EPSILON
class Vector:
def __init__(self, lst):
"""
__init__ 代表類的構(gòu)造函數(shù)
雙下劃線開頭的變量 例如_values,代表類的私有成員
lst是個(gè)引用,list(lst)將值復(fù)制一遍,防止用戶修改值
"""
self._values = list(lst)
def dot(self, another):
"""向量點(diǎn)乘,返回結(jié)果標(biāo)量"""
assert len(self) == len(another), \
"Error in dot product. Length of vectors must be same."
return sum(a * b for a, b in zip(self, another))
def norm(self):
"""返回向量的模"""
return math.sqrt(sum(e**2 for e in self))
def normalize(self):
"""
歸一化,規(guī)范化
返回向量的單位向量
此處設(shè)計(jì)到了除法: def __truediv__(self, k):
"""
if self.norm() < EPSILON:
raise ZeroDivisionError("Normalize error! norm is zero.")
return Vector(self._values) / self.norm()
# return 1 / self.norm() * Vector(self._values)
# return Vector([e / self.norm() for e in self])
def __truediv__(self, k):
"""返回?cái)?shù)量除法的結(jié)果向量:self / k"""
return (1 / k) * self
@classmethod
def zero(cls, dim):
"""返回一個(gè)dim維的零向量
@classmethod 修飾符對應(yīng)的函數(shù)不需要實(shí)例化,不需要 self 參數(shù),但第一個(gè)參數(shù)需要是表示自身類的cls參數(shù),可以來調(diào)用類的屬性,類的方法,實(shí)例化對象等。
"""
return cls([0] * dim)
def __add__(self, another):
"""向量加法,返回結(jié)果向量"""
assert len(self) == len(another), \
"Error in adding. Length of vectors must be same."
# return Vector([a + b for a, b in zip(self._values, another._values)])
return Vector([a + b for a, b in zip(self, another)])
def __sub__(self, another):
"""向量減法,返回結(jié)果向量"""
assert len(self) == len(another), \
"Error in subtracting. Length of vectors must be same."
return Vector([a - b for a, b in zip(self, another)])
def __mul__(self, k):
"""返回?cái)?shù)量乘法的結(jié)果向量:self * k"""
return Vector([k * e for e in self])
def __rmul__(self, k):
"""
返回?cái)?shù)量乘法的結(jié)果向量:k * self
self本身就是一個(gè)列表
"""
return self * k
def __pos__(self):
"""返回向量取正的結(jié)果向量"""
return 1 * self
def __neg__(self):
"""返回向量取負(fù)的結(jié)果向量"""
return -1 * self
def __iter__(self):
"""返回向量的迭代器"""
return self._values.__iter__()
def __getitem__(self, index):
"""取向量的第index個(gè)元素"""
return self._values[index]
def __len__(self):
"""返回向量長度(有多少個(gè)元素)"""
return len(self._values)
def __repr__(self):
"""打印顯示:Vector([5, 2])"""
return "Vector({})".format(self._values)
def __str__(self):
"""打印顯示:(5, 2)"""
return "({})".format(", ".join(str(e) for e in self._values))
_globals.py
# 包中的變量,但是對包外不可見,因此使用“_”開頭
EPSILON = 1e-8
main_vector.py
from playLA.Vector import Vector
if __name__ == "__main__":
vec = Vector([5, 2])
print(vec)
print("len(vec) = {}".format(len(vec)))
print("vec[0] = {}, vec[1] = {}".format(vec[0], vec[1]))
vec2 = Vector([3, 1])
print("{} + {} = {}".format(vec, vec2, vec + vec2))
print("{} - {} = {}".format(vec, vec2, vec - vec2))
print("{} * {} = {}".format(vec, 3, vec * 3))
print("{} * {} = {}".format(3, vec, 3 * vec))
print("+{} = {}".format(vec, +vec))
print("-{} = {}".format(vec, -vec))
zero2 = Vector.zero(2)
print(zero2)
print("{} + {} = {}".format(vec, zero2, vec + zero2))
print("norm({}) = {}".format(vec, vec.norm()))
print("norm({}) = {}".format(vec2, vec2.norm()))
print("norm({}) = {}".format(zero2, zero2.norm()))
print("normalize {} is {}".format(vec, vec.normalize()))
print(vec.normalize().norm())
print("normalize {} is {}".format(vec2, vec2.normalize()))
print(vec2.normalize().norm())
try:
zero2.normalize()
except ZeroDivisionError:
print("Cannot normalize zero vector {}.".format(zero2))
print("========點(diǎn)乘:========")
print(vec.dot(vec2))
main_numpy_vector.py
import numpy as np
if __name__ == "__main__":
print(np.__version__)
# np.array 基礎(chǔ)
print("========np.array 基礎(chǔ)========")
lst = [1, 2, 3]
lst[0] = "Linear Algebra"
print(lst)
print("========vec = np.array([1, 2, 3])========")
vec = np.array([1, 2, 3])
print(vec)
# vec[0] = "Linear Algebra"
# vec[0] = 666
# print(vec)
print("========np.array的創(chuàng)建========")
# np.array的創(chuàng)建
print(np.zeros(5))
print(np.ones(5))
print(np.full(5, 666))
print("========np.array的基本屬性========")
# np.array的基本屬性
print(vec)
print("size =", vec.size)
print("size =", len(vec))
print(vec[0])
print(vec[-1])
print(vec[0: 2])
print(type(vec[0: 2]))
print("========np.array的基本運(yùn)算========")
# np.array的基本運(yùn)算
vec2 = np.array([4, 5, 6])
print("{} + {} = {}".format(vec, vec2, vec + vec2))
print("{} - {} = {}".format(vec, vec2, vec - vec2))
print("{} * {} = {}".format(2, vec, 2 * vec))
print("沒有數(shù)學(xué)意義的乘法:{} * {} = {}".format(vec, vec2, vec * vec2))
print("{}.dot({}) = {}".format(vec, vec2, vec.dot(vec2)))
print("========求模========")
print(np.linalg.norm(vec))
print("========歸一化========")
print(vec / np.linalg.norm(vec))
print("========單位向量========")
print(np.linalg.norm(vec / np.linalg.norm(vec)))
print("========零向量會報(bào)錯(cuò)========")
zero3 = np.zeros(3)
print(zero3 / np.linalg.norm(zero3))
到了這里,關(guān)于線性代數(shù)-Python-01:向量的基本運(yùn)算 - 手寫Vector及numpy的基本用法的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!