Python 如何解決稀疏矩陣運算
用Python求解微分線性方程
因為之前用matlab也編寫過,所以前不久試著用python寫,感覺之間互通點也蠻多的,易理解。
題目:稀疏線性方程組的求解方法
簡單的方程如: AX=b
其中
python有很多功能庫,這些庫對於編程很有幫助,可以在pycharm的Project Interpreter導入庫,例如numpy、os、scipy等比較基礎的庫,
下面是用來求解的代碼:
import numpy as np from scipy import linalg import os #輸入矩陣維數 print("你好,這裡是計算稀疏矩陣線性方程組的地方,非誠勿擾!") dism_num = input("你的A矩陣維數是:") dism_num = int(dism_num) print("接下來請你依次輸入矩陣的行向量(註意隻能輸入英文逗號,):") A =[] #X =[] for i in range(1,dism_num+1): a=input("第"+str(i)+"行向量是:") alist = a.split(",") alist = [int(alist[j]) for j in range(len(alist))] A.append(alist) print("你所輸入的矩陣行向量是:") print(A) #記錄輸入的X矩陣 #輸入向量b print("輸入b向量") b = input("b向量是:") b_list = b.split(",") b_list = [int(b_list[j]) for j in range(len(b_list))] print("你輸入的b向量是:") print(b_list) #記錄b向量 #詢問是否計算單個答案(單元素) ask = input("是否隻需求解單個值:(是或否)") while(True): if ask == '是': ask_a = 'T' ask_num = input("請繼續輸入你所需要的答案序號:") ask_num = int(ask_num) if ask_num<=dism_num and ask_num>0: print("OK,馬上幫你計算") break else: print("輸入的值超出矩陣維數,請重新輸入:") if ask == '否': ask_a = 'F' break #詢問完成,隻有當用戶輸入正確的序號才可以進行計算,否則重新詢問 #開始計算x向量瞭 A = np.array(A) b = np.array(b_list) x = linalg.solve(A,b) print("計算的結果的:") if ask_a == 'F': print(x) if ask_a =='T': print(x[ask_num-1]) #計算完x向量瞭 os.system("pause") #用於py文件結束玩暫停顯示結果
其基本流程如圖:
運行結果如下:
補充:python 多線程稀疏矩陣乘法
看代碼吧~
import threading, time import numpy as np res = [] class MyThread(threading.Thread): def __init__(self,i,j,m1,m2): threading.Thread.__init__(self) self.x, self.y = i,j self.m1, self.m2 = m1, m2 def run(self): global res, lock if lock.acquire(): m1 = self.m1[self.m1[:,0]==self.x] m2 = self.m2[self.m2[:,1]==self.y] value = 0. for item1 in m1: for item2 in m2: if item1[1] == item2[0]: value += item1[2]*item2[2] res.append([self.x,self.y,value]) lock.release() if "__main__" == __name__: m1 = [[2,2],[0,0,1],[0,1,2],[1,0,3],[1,1,4]] m2 = [[2,3],[0,0,2],[0,2,1],[1,2,3],[1,1,4]] s1, s2 = m1[0], m2[0] assert s1[1]==s2[0], 'mismatch' m1_value = np.array(m1[1:]) m2_value = np.array(m2[1:]) rows, cols = s1[0], s2[1] res.append([rows, cols]) ThreadList = [] lock = threading.Lock() for i in range(rows): for j in range(cols): t = MyThread(i,j,m1_value,m2_value) ThreadList.append(t) for t in ThreadList: t.start() for t in ThreadList: t.join() print (res)
以上為個人經驗,希望能給大傢一個參考,也希望大傢多多支持WalkonNet。